File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 练习python的递归函数
2
+
3
+
4
+ # 用递归来求阶乘
5
+ def func (num ):
6
+ if num == 1 :
7
+ return 1
8
+ return func (num - 1 )* num
9
+
10
+
11
+ # 求100的阶乘
12
+ num = 100
13
+ n = func (num )
14
+ print ('%d的阶乘是' % (num ,), n )
15
+
16
+
17
+ # 上面的函数如果n的数字过大的话就会出现栈溢出的问题,这是我们需要通过尾递归来优化
18
+ def fact (num , product = 1 ):
19
+ if num == 1 :
20
+ return product
21
+ return fact (num - 1 , num * product )
22
+
23
+
24
+ # 虽然做了尾递归优化,但是该语言底层没有弄优化,所以还是求不了1000的阶乘
25
+ num = 500
26
+ n = fact (num )
27
+ print ('%d的阶乘是' % (num ,), n )
28
+
29
+
30
+ # 最后的作业,练习汉诺塔:move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法
31
+ def move (n , a , b , c ):
32
+ if n == 1 :
33
+ print (a , '-->' , c )
34
+ else :
35
+ # 借助c柱将a的移动到c
36
+ move (n - 1 , a , c , b )
37
+ # 借助b柱将a的最后一根移动到c
38
+ move (1 , a , b , c )
39
+ # 最后将b柱的借助a柱移动到c柱
40
+ move (n - 1 , b , a , c )
41
+
42
+
43
+ move (3 , 'A' , 'B' , 'C' )
44
+
You can’t perform that action at this time.
0 commit comments