def factorial(n):
if n <= 1:
return 1
else:
return n* factorial(n-1)
print(factorial(6))
print(factorial(5))
# 1 * 2 * 3 * 4 * 5 * 6
def sum_naturals(n):
if n in [0, 1]:
return n
else:
return n + sum_naturals(n-1)
print(sum_naturals(0))
print(sum_naturals(1))
print(sum_naturals(5))
def remeber_fact(n0, product):
if n0 <= 1:
return product
else:
return remeber_fact(n0-1, product*n0)
print(remeber_fact(0, 1))
print(remeber_fact(0, 10))
print(remeber_fact(1, 1))
# 第一个数是 0, 1 返回第二个数
# 第一个数大于 1 返回的是
print(remeber_fact(4, 5))
# remeber_fact(n0-1, product*n0)
# remeber_fact(4, 5)
# remeber_fact(3, 5*4)
# remeber_fact(2, 5*4*3)
# remeber_fact(1, 5*4*3*2)
def factorial2(n):
return remeber_fact(n, 1)
print(factorial2(6))
# remeber_fact(n0-1, product*n0)
# remeber_fact(6, 1)
# remeber_fact(5, 1*6)
# remeber_fact(4, 1*6*5)
# remeber_fact(3, 1*6*5*4)
# remeber_fact(2, 1*6*5*4*3)
# remeber_fact(1, 1*6*5*4*3*2)
# 求列表中所有的偶数累加和
def sum_acc(s, r):
if r == []:
return s
elif r[0] % 2 == 0:
return sum_acc(s + r[0], r[1:])
else:
return sum_acc(s, r[1:])
def sum_evens(L):
return sum_acc(0, L)
print(sum_evens([3, 4, 5, 4]))
print(sum_evens([]))
def count(s, char):
if s == '':
return 0
else:
is_char = 0
if s.find(char) ==0 and char != '' :
is_char += 1
return count(s[1:], char) + is_char
print(count("", "")) # 0
print('"',count("banana", "")) # 0
print(count("banana", "a")) # 3
print(count("banana", "z")) #0
def count_acc(s, char, acc):
if s == '':
return acc
else:
is_char = 0
if s.find(char) ==0 and char != '' :
is_char += 1
return count_acc(s[1:], char, acc+is_char)
def count_letters(s, char):
return count_acc(s, char, 0)
print(count_letters("", "")) # 0
print('"',count_letters("banana", "")) # 0
print(count_letters("banana", "a")) # 3
print(count_letters("banana", "z")) #0
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
# 奇数和
def sum_odd(L):
if L == []:
return 0
else:
if L[0]%2== 1:
return L[0] + sum_odd(L[1:])
return sum_odd(L[1:])
print(sum_odd([])) # 0
print(sum_odd([1])) # 1
print(sum_odd([1, 2, 3])) # 4
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def filter_odd(L):
if L==[]:
return []
else:
if L[0]%2 !=0:
return [L[0]] + filter_odd(L[1:])
else:
return filter_odd(L[1:])
print(filter_odd([]))
print(filter_odd([1, 2, 3]))
print(filter_odd([2, 4, 6, 8]))
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def inverse(L):
if L == []:
return []
else:
return [L[-1]] + inverse(L[:-1])
pass
print(inverse([]))
print(inverse([1, 2, 3]))
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def product(L):
if L ==[]:
return 1
else:
return L[0]*product(L[1:])
print(product([]))
print(product([3]))
print(product([2, 3, 5]))
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def mul_table(n):
if n <= 0 :
return [[0]]
else:
return [[mul_table(n-1)]]
print(mul_table(0))
print(mul_table(1))
print(mul_table(2))
网友评论