Python - Recursion(factorial、reverse、fibonacci、hanoi)
程序员文章站
2022-05-18 20:26:09
...
def factorial(n):
if n<=1:
return 1
else:
return factorial(n-1)*n
if __name__ == "__main__":
print(factorial(3))
def Reverse(n):
'''
n is a number
'''
print(n%10,end='')
if n>10:
return Reverse(n//10)
if __name__ == "__main__":
Reverse(12345)
#--------------------------------------------------------------------------
def Closure(n):
result = []
def Reverse(n):
'''n is a number'''
result.append(n%10)
if n>10:
return Reverse(n//10)
return result
return Reverse
if __name__ == "__main__":
data = 1234567
Reverse = Closure(data)
result = Reverse(data)
reverse_data = 0
for i,j in enumerate(result):
reverse_data += j*(10**(len(result)-i-1))
print(reverse_data)
#需求:输入n(Index),输出fibonacci的第n个数据
def fibonacci_recursion(n):
if n<2:
return 1
else:
return fibonacci_recursion(n-1)+fibonacci_recursion(n-2)
def fibonacci(n):
f1 = f2 = 1
for i in range(1,n):
f1,f2 = f2,f1+f2
return f2
if __name__ == "__main__":
print("fibonacci[%d] = %d" % (10,fibonacci_recursion(10)))
print("fibonacci[%d] = %d" % (20,fibonacci(20)))
def hanoi(n,x,y,z):
if n==1:
print(n,':',x,"->",z)
else:
hanoi(n-1,x,z,y)
print(n,':',x,"->",z)
hanoi(n-1,y,x,z)
if __name__ == "__main__":
hanoi(3,'A','B','C')
上一篇: 437. Path Sum III