2018-07-28
递归函数以及尾递归优化:
#利用递归函数计算阶乘
... #N! = 1 * 2 * 3 * 4 * ... * N
... def fact(n):
... if n == 1:
... return 1
... return n * fact(n-1)
...
>>> print('fact(1)=',fact(1))
fact(1)= 1
>>> print('fact(5)=',fact(5))
fact(5)= 120
>>>
>>> print('fact(10)=',fact(10))
fact(10)= 3628800
#利用递归函数移动汉诺塔:
... def move(n,a,b,c):
... if n == 1:
... print('move',a,'..>',c)
... else:
... move(n-1,a,c,b)
... move(1,a,b,c)
... move(n-1,b,a,c)
...
>>> move(4,'A','B','C')
move A ..> B
move A ..> C
move B ..> C
move A ..> B
move C ..> A
move C ..> B
move A ..> B
move A ..> C
move B ..> C
move B ..> A
move C ..> A
move B ..> C
move A ..> B
move A ..> C
move B ..> C
尾递归优化方法:需要多一点代码,主要是要把每一步的乘积传入到递归函数中:
def fact(n):
... return fact_iter(n,1)
...
>>> def fact_iter(num,product):
... if num == 1:
... return product
... return fact_iter(num - 1,num * product)
切片函数的使用:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print('L[0:3] =', L[0:3])
print('L[:3] =', L[:3])
print('L[1:3] =', L[1:3])
print('L[-2:] =', L[-2:])
R = list(range(100))
print('R[:10] =', R[:10])
print('R[-10:] =', R[-10:])
print('R[10:20] =', R[10:20])
print('R[:10:2] =', R[:10:2])
print('R[::5] =', R[::5])