def TowerOfHanoi(n,OriginalPillar,DestinationPillar,IntermediaryPillar):
if n==1:
print("碟 1 從柱",OriginalPillar," 到柱",DestinationPillar)
return
TowerOfHanoi(n-1,OriginalPillar,IntermediaryPillar,DestinationPillar)
print("碟",n,"從柱",OriginalPillar," 到柱",DestinationPillar)
TowerOfHanoi(n-1,IntermediaryPillar,DestinationPillar,OriginalPillar)
#第n個之上(n-1),從A-->B
#第n個 ,從A-->C
#第n個之上(n-1),從B-->C
TowerOfHanoi(3,"A","C","B")
print("完成!")
------------------------------------------
碟 1 從柱 A 到柱 C
碟 2 從柱 A 到柱 B
碟 1 從柱 C 到柱 B
碟 3 從柱 A 到柱 C
碟 1 從柱 B 到柱 A
碟 2 從柱 B 到柱 C
碟 1 從柱 A 到柱 C
完成!
==========================================================
參考解說
https://www.youtube.com/watch?v=oV2C9UINg_U
cnt=0
def HanoiTower(n,fro,mid,des):
global cnt
if n==1:
#移動時才累計
cnt+=1
#只有一個碟A-->C
print("Move",cnt,"disk",n,"from",fro,"to",des)
else:
#第n個碟之前(n-1),所有碟A-->B
HanoiTower(n-1,fro,des,mid)
#移動時才累計
cnt+=1
#第n個碟(n),A-->C
print("Move",cnt,"disk",n,"from",fro,"to",des)
#第n個碟之前(n-1),所有碟B-->C
HanoiTower(n-1,mid,fro,des)
HanoiTower(3,"A","B","C")
------------------------------------------
Move 1 disk 1 from A to C
Move 2 disk 2 from A to B
Move 3 disk 1 from C to B
Move 4 disk 3 from A to C
Move 5 disk 1 from B to A
Move 6 disk 2 from B to C
Move 7 disk 1 from A to C
==========================================================
def prime_factorization(n):
if n==1:
return[]
for f in range(2,n+1):
if n%f==0:
return [f]+prime_factorization(n//f)
print(prime_factorization(3080))
------------------------------------------
[2, 2, 2, 5, 7, 11]
==========================================================
------------------------------------------
==========================================================
------------------------------------------
==========================================================
------------------------------------------
==========================================================