Python Yield From 实现递归汉诺塔

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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值