21.求最大公因数
def func(a,b):
if a==b:
return a
else:
num=min(a,b)
while a % num !=0 or b % num !=0:
num-=1
return num
print(func(12,18))
或者
def func(a,b):
while b != 0:
a,b=b,a%b
return a
print(func(12,18))
22.快乐数
def change(x):
sum = 0
while x >0:
j = x%10
sum+=j*j
x //= 10
return sum
def happynumber(n):
while n >9:
n=change(n)
if n ==1:
return True
else:
return False
print(happynumber(19))
23.求立方根并向下取整
import math
def func(n):
result = math.pow(n,1/3)
# math.pow(x,y):返回x的y次方
# math.sqrt(x):返回x的平方根
return int(result) # int 可以向下取整
print(func(9))
24.字符串转换
我的程序:
str1="Hello World Python"
lst=str1.split()
lst=lst[::-1]
str2=" ".join(lst)
str3=""
for i in range(len(str2)):
if str2[i].isupper()==True:
b=str2[i].lower()
str3+=b
elif str2[i].isupper()!=True:
b = str2[i].upper()
str3 += b
else:
b=""
str3+=b
print(str3)
别人程序:
def func(s):
l = s.split(" ")
l=l[::-1]
s=""
for i in l:
i=i.swapcase()
s+=i
s+=" "
return s[0:len(s)-1]
print(func("Hello Python"))
25.旋转字符串
思路:hello,从e后面分开,那么就变成了llohe。
两个hello拼在一起,就是hellohello,那么llohe肯定在两个字符串拼成的新的字符串里面。
def func(a,b):
if len(a) != len(b):
return False
else:
bigA = a+a
result = b in bigA
return result
print(func("hello","llohe"))
26.判断子序列
给定两个字符串S和T,判断s是否是T的子序列,即是否可以从T删除一些字符换成s
def func(S,T):
a=""
if len(S) >= len(T):
return False
else:
for i in T:
for j in S:
if i == j:
a+=i
else:
a+=""
if S==a:
return True
else:
return False
print(func("eo","hello"))
27.字符串的相邻字符去重
给定一个仅右英文小写字母组成的字符串s,将相邻且相同的两个字符删掉构成新的字符串,重复删除操作直至生成不符合删除条件的字符串并返回。
输入:acbbc
输出:a
def func(s):
res = ""
for i in s:
if res == "":
res += i
elif res[-1] == i:
res = res[:-1]
else:
res += i
return res
print(func("acbbc"))
28.最长公共子串
给定两个字符串str1和str2,输出两个字符串的最长公共子串,保证str1和str2的最长公共子串存在且唯一
def lcs(str1,str2):
res = ""
left = 0
for i in range(len(str1)+1):
if str1[left:i+1] in str2:
res = str1[left:i+1]
else:
left += 1
return res
print(lcs("hellopython","goodllopylike"))
29.冒泡排序
a=[80,58,73,90,31,92,39,24,14,79,46,61,31,61,93,62,11,52,34,17]
for i in range(len(a)):
for j in range(len(a)-1-i):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print(a)
30.选择排序
a=[80,58,73,90,31,92,39,24,14,79,46,61,31,61,93,62,11,52,34,17]
for i in range(len(a)-1):
min_index = i
for j in range(i,len(a)):
if a[min_index]>a[j]:
min_index = j
a[min_index],a[i]=a[i],a[min_index]
print(a)