Python-递归
# 设置递归深度 # sys.setrecursionlimit(1000) # 求阶乘 # 1.非递归版本 def factorial(n): result = n for i in range(1, n): result *= i continue print(n, '的阶乘为:', result) print(factorial(10)) # 2.递归版本(求n的阶乘) def factorial1(n): if n ==1: return 1 else: return n * factorial1(n - 1) n = int(input('请输入一个正整数:')) answer = factorial1(n) print(n, '的阶乘为:', answer) # 斐波那契数列 # 1.递归版本 def fun1(n): if n == 1 or n ==2: return 1 else: return fun1(n-1) + fun1(n-2) for n in range(1,20): a = fun1(n) print('斐波那契数列的第', n, '位是',a) # 2.迭代版本 def fun2(n): n1 = 1 n2 = 1 n3 = 1 if n < 1: print('输入有误,请重新输入!') return -1 else: while n - 2 > 0: n3 = n1 + n2 n1 = n2 n2 = n3 n -= 1 return n3 n = int(input('请输入已经经过的月份:')) result = fun2(n) if result !=-1: print('总共有%d只小兔崽子'% result) # 汉诺塔游戏 def hanoi(n, x, y, z):#x:初始位置;y:目标位置;z:借用位置 if n == 1: print(x, '-->', z) else: hanoi(n-1, x, z, y)# 将n-1个盘子从X移到Y print(x, '-->', z) #将第n个盘子从X移到Z hanoi(n-1, y, x, z)# 将n-1个盘子从Y移到Z n = int(input('请输入汉诺塔的层数:')) hanoi(n, 'a', 'b', 'c')