1. 斐波那契数列的实现
1.1 迭代实现
def Rabbit(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print('输入有误')
return -1
while (n-2) > 0:
n3 = n2 + n1
n1 = n2
n2 = n3
n -= 1
return n3
result = Rabbit(20)
if result != -1:
print('总共有%d对小兔子诞生!'% result)
1.2 递归实现
def Rabbit(n):
if n < 1:
print('输入有误!')
return -1
if n == 1 or n == 2:
return 1
else:
return Rabbit(n-1) + Rabbit(n-2)
result = Rabbit(20)
if result != -1:
print('总共有%d对小兔子诞生!'% result)
2 汉诺塔,递归方式解决玩法
#汉诺塔的实现——递归
def hanoi(n,A,B,C):
if n == 1:
print(A,'----->',C)
else:
hanoi(n-1,A,C,B)#将前n-1个盘子从A移动到B上
print(A,'----->',C)#将最底下的最后一个盘子从X移动到C上
hanoi(n-1,B,A,C)#将B上的n-1个盘子移动到C上
n = int(input('请输入汉诺塔的层数:'))
hanoi(n,'A','B','C')