[Life Bitter short PYTHON song] -- PYTHON functional programming 03, python03
Python Recursion
If a function calls itself internally, this function is a recursive function;
The following is a classic example: Using Python Recursion to find factorial
def fact(j): sum=0 if j==0: sum=1 else: sum=j*fact(j-1) return sumfor i in range(5): print('%d!=%d'%(i,fact(i)))
Remove general recursion after CPS transformation,
id=lambda x:xdef factCPS(n): def f(n,k): if n==0: return k(1) else: return f(n-1,lambda x:k(n*x)) return f(n,id)
Tail recursion Optimization
Tail recursion is based on the function's End call. Each level of call directly returns the function's return value to update the call stack, instead of creating a new call stack, similar to iterative implementation, optimized General recursion in time and space;
def fact(n,sum=0) if n==0: return sum else: return fact(n-1,sum+n)