forked from Jack-Lee-Hiter/AlgorithmsByPython
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.py
More file actions
Latest commit
38 lines (31 loc) · 927 Bytes
/
Copy pathRecursion.py
File metadata and controls
38 lines (31 loc) · 927 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 递归求和
deflistSum(numlist):
iflen(numlist) ==1:
returnnumlist[0]
else:
returnnumlist[0] +listSum(numlist[1:])
print(listSum([1, 2, 3, 4, 5, 6, 7]))
# 递归求阶乘
deflistFactorial(num):
ifnum<=1:
return1
else:
returnnum*listFactorial(num-1)
print(listFactorial(10))
# 递归实现进制转换:
deftoStr(n,base):
convertString="0123456789ABCDEF"
ifn<base:
returnconvertString[n]
else:
returntoStr(n//base, base) +convertString[n%base]
print(toStr(1453, 16))
# 递归实现Hanoi塔
defHanoi(fromPole, withPole, toPole, diskNum):
ifdiskNum<=1:
print("moving disk from %s to %s"% (fromPole, toPole))
else:
Hanoi(fromPole, toPole, withPole, diskNum-1)
print("moving disk from %s to %s"% (fromPole, toPole))
Hanoi(withPole, fromPole, toPole, diskNum-1)
Hanoi('A', 'B', 'C', 3)