Usually recursion involves a function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions to problems that may otherwise be very difficult to program.
A recursive algorithm must call itself, recursively.
base case 是指递归算法需要有一个标识终止递归的状态,避免无限递归循环下去。而这个 base case 就是一个“最小直接解决问题”的单位。
In [4]:
def reverse(s):
if len(s) == 0: # 有一个 base case 来终止递归
return ''
else:
return s[-1] + reverse(s[:-1]) ## 满足第二、三条定律,每次递归都更进一步,并且是自我调用。
assert reverse('apple') == 'elppa'
In [8]:
import re
def removeWhite(s):
return re.sub(r'[\W]', '', s)
def isPal(s):
if len(s) <= 1:
return True
else:
if s[0] == s[-1]:
return isPal(s[1:-1])
else:
return False
assert isPal(removeWhite("x")) is True
assert isPal(removeWhite("radar")) is True
assert isPal(removeWhite("hello"))is False
assert isPal(removeWhite(""))is True
assert isPal(removeWhite("hannah")) is True
assert isPal(removeWhite("madam i'm adam")) is True
递归实际就是压栈的操作。将递归执行的函数依次压入栈中,然后再依次弹出结果。
汉诺塔是一个非常典型的利用递归的思想解决问题的例子:
In [3]:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print "moving disk from",fp,"to",tp
moveTower(3,"A","B","C")