1.编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值。
>>> def power(x, y):
'计算并返回 x 的 y 次幂'
result = 1
for i in range(y):
result *= x
return result
>>> power(2, 3)
8
2.编写一个函数,利用欧几里得算法求最大公约数,例如gcd(x, y)返回值为参数x和参数y的最大公约数。
>>> def gcd(x, y):
'用欧几里得算法求最大公因数'
while y:
t = x % y
x = y
y = t
return x
>>> gcd(1234,49)
1
3.编写一个将十进制转换为二进制的函数,要求采用“除2取余”的方式,结果与调用bin()一样返回字符串形式。
>>> def DectoBin(dec):
'是一个将十进制转换为二进制的函数'
list1 = []
str1 = ''
while dec:
quo = dec % 2
list1.append(quo)
dec = dec // 2
while list1:
str1 += str(list1.pop())
return str1
>>> DectoBin(26)
'11010'
4.编写一个计算并输出所有参数的和乘以基数(默认为3)的函数。
>>> def myfun(*p, base = 3):
result = 0
for each in p:
result += each
result *= base
return result
>>> myfun(1,2,3,4)
30
5.如果一个三位数等于其各位数字的立方和,则这个数被称为水仙花数。编写一个程序,找出所有的水仙花数。
>>> def myfun():
for each in range(100, 1000):
temp = each
sum0 = 0
while temp:
sum0 = sum0 + (temp%10) ** 3
temp = temp // 10
if sum0 == each:
print(each)
>>> myfun()
153
370
371
407
6.编写一个函数findstr(),该函数统计一个长度为2的字符串在另一个字符串中出现的次数。
>>> def findstr(des_str, sub_str):
count = 0
length = len(des_str)
if sub_str not in des_str:
print('在目的字符串中未出现指定字符串')
else:
for each in range(length - 1):
if des_str[each] == sub_str[0]:
if des_str[each + 1] == sub_str[1]:
count +=1
print('在目的字符串中,指定字符串共出现 %d 次' % count)
>>> str1 = 'You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.'
>>> str2 = 'im'
>>> findstr(des_str = str1, sub_str = str2)
在目的字符串中,指定字符串共出现 3 次