案例一:汉诺塔
例一:
def move(n, a, buffer, c): if n ==1: print('move', a, '-->', c) else: move(n-1, a, c, buffer) move(1, a, buffer, c) move(n-1, buffer, a, c) move(3, 'A','B','C')
例二:
def hanoi(n,x,y,z): if n == 1: print(x,'--->',z) else: hanoi(n-1,x,z,y)#将前n-1个盘子移动到y上 print(x, '--->', z)#将最底下的盘子移动到z上 hanoi(n-1,y,x,z)#将y上的n-1个盘子移动到z上 if __name__ == '__main__': num = int(input("请输入汉若塔层数:")) hanoi(num,'X','buffer','Z')
案例二:求阶乘
例一:
def f(n): if n == 0: sum = 1 else: sum = n * f(n-1) return sum s = int(input('输入一个整数:')) p = f(s) print('%s!=%s' % (s,p))
例二:
def factorial(n): res = n for i in range(1,n): res *= i return res if __name__ == '__main__': num = int(input("请输入一个正整数:")) result = factorial(num) print("%s的阶乘为:%s" % (num,result))
案例三:利用递归将输入的字符串反向输出
def output(str,len): if len == 0: return print(str[len-1]) output(str,len-1) s = input("请输入字符串:") l = len(s) output(s,l)