recur.py 488 B

123456789101112131415161718192021222324
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # 利用递归函数计算阶乘
  4. # N! = 1 * 2 * 3 * ... * N
  5. def fact(n):
  6. if n == 1:
  7. return 1
  8. return n * fact(n-1)
  9. print('fact(1) =', fact(1))
  10. print('fact(5) =', fact(5))
  11. print('fact(10) =', fact(10))
  12. # 利用递归函数移动汉诺塔:
  13. def move(n, a, b, c):
  14. if n == 1:
  15. print('move', a, '-->', c)
  16. else:
  17. move(n-1, a, c, b)
  18. move(1, a, b, c)
  19. move(n-1, b, a, c)
  20. move(4, 'A', 'B', 'C')