import time
class Hanoi(object):
def __init__(self,layers):
#self.layers 表示层数。
self.layers=layers
#以队列表示汉诺塔的三个柱子。
self.pillars = [[],[],[]]
self.move_counts=0
for i in range(self.layers):
self.pillars[0].append(i)
print("%d Layer Hanoi Tower Set Ready."%(self.layers))
def move(pillars,start_pillar_slice,start_index=0,end_index=2):
global move_counts
if len(start_pillar_slice)==0:exit
if len(start_pillar_slice)==1:
#print("before pillars are %s"%(str(pillars)))
#print("move %s from pillar[%s] --> pillar[%s]."%(str(start_pillar_slice),str(start_index),str(end_index)))
temp_last_piece=pillars[start_index].pop(0)
pillars[end_index].insert(0,temp_last_piece)
#print("after pillars are %s"%(str(pillars)))
move_counts += 1
yield
else:
temp_end_index_set = set((0,1,2))-set((start_index,end_index))
temp_end_index=temp_end_index_set.pop()
if start_pillar_slice[:-1]:
new_slice = start_pillar_slice[:-1]
else:
new_slice = start_pillar_slice
#print("1. Pillars are %s"%(str(pillars)),"start_index=%d"%(start_index)," end_index=%d"%(temp_end_index)," start_pillar_slice=%s"%(str(new_slice)))
yield from move(pillars,new_slice,start_index,temp_end_index)
#print("2. Pillars are %s"%(str(pillars)),"start_index=%d"%(start_index)," end_index=%d"%(end_index)," start_pillar_slice=%s"%(str([start_pillar_slice[-1]])))
yield from move(pillars,[start_pillar_slice[-1]],start_index,end_index)
#print("3. Pillars are %s"%(str(pillars)),"start_index=%d"%(temp_end_index)," end_index=%d"%(end_index)," start_pillar_slice=%s"%(str(new_slice)))
yield from move(pillars,new_slice,temp_end_index,end_index)
if __name__ == "__main__":
move_counts=0
t1 = time.time()
hanoi=Hanoi(24)
a = list(move(hanoi.pillars,hanoi.pillars[0],0,2))
t2 = time.time()
print("Time used: %d"%(t2-t1)," Total moves = %s"%(str(move_counts))
Python Yield From 实现递归汉诺塔
最新推荐文章于 2024-07-25 18:55:58 发布