# 计算100以内的累加,分别使用递归和for循环 # 递归累加 def sum(n: int): if n <= 1: return 1 else: return sum(n - 1) + n print(sum(10)) # for 循环累加 sum = 0 for i in range(1,101): sum+=i print(sum) # 递归乘法 def sum(n: int): if n <= 1: return 1 return sum(n-1) * n print(sum(10)) # for循环乘法 sum = 1 for i in range(1,10): sum*=i print(sum) # 斐波那契数列 def fun(n): if n <= 2: return 1 return fun(n-1) + fun(n - 2) print(fun(4)) # 有n步台阶,一次只能上1步或2步,共有多少种走法上楼梯 # 和斐波那契数一样的处理方法 a , b = 0,1 for sum in range(1,1): a,b = b,a + b print(b) # 使用reduce进行累计计算 def sum(x,y): return x + y print(reduce(sum,range(1,11))) print(reduce(lambda x, y : x * y, range(1, 11))) print(reduce(lambda x, y : x + y, range(1, 11)))
标签:递归,int,sum,累加,循环,100 From: https://www.cnblogs.com/grapefruit0201/p/16747087.html