河内带有“柜台"的塔楼在python中 [英] Towers of Hanoi with "counter" in python

查看:112
本文介绍了河内带有“柜台"的塔楼在python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python编写了河内之塔"的代码,我试图添加一个计数器以显示其运行了多少次.我尝试了一些事情,如while循环和for循环等,但是它不起作用.我敢肯定,答案很简单,但我的大脑目前正在最低的设置上运行.我的代码如下:

I have written a code for "Towers of Hanoi" in python and I am trying to add a counter to show how many times it has run. I tried several things like a while loop and for loops etc. but it doesn't work. I am sure that the answer is pretty easy but my brain is running on the lowest setting right now. My code looks like this:

def Hanoi(n, src, dst, tmp):
if n > 0:
    Hanoi(n - 1, src, tmp, dst)
    print "Move disc", chr(64 + n), "From tower", src, "to tower", dst
    Hanoi(n - 1, tmp, dst, src)

Hanoi(4,0,2,1) #Just an example

我知道代码必须运行(2 ^ n)-1次,但我只是无法实现它.因为我编写代码的方式,所以值n会发生变化,因此对我有用. (我尝试过这样的事情:

I know that the code has to run (2^n)-1 times, but I just cant implement it. Because the way I wrote the code the value n changes so that would work for me. (I tried something like this:

def Hanoi(n, src, dst, tmp):

    a = 0
    while (a < (2**n)-1)
        a+=1

    if n > 0:
        Hanoi(n - 1, src, tmp, dst)
        print a, "Move disc", chr(64 + n), "From tower", src, "to tower", dst
        Hanoi(n - 1, tmp, dst, src)

但是正如我所说,值n会发生变化,我不知道如何解决它.

but as I've said, the value n changes and I don't know how to fix it.

为澄清起见,我希望它购买如下步骤:(如果我呼叫Hanoi(3,0,2,1))

To clarify, I want it to shop the number of steps like this: (If I call Hanoi(3,0,2,1))

1. Move disc A From tower 0 to tower 2
2. Move disc B From tower 0 to tower 1
3. Move disc A From tower 2 to tower 1
4. Move disc C From tower 0 to tower 2
5. Move disc A From tower 1 to tower 0
6. Move disc B From tower 1 to tower 2
7. Move disc A From tower 0 to tower 2

推荐答案

如何从函数中返回调用次数:

How about returning the number of calls from your function:

def Hanoi(n, src, dst, tmp):
    if n > 0:
        pre = Hanoi(n - 1, src, tmp, dst)
        print "Move disc", chr(64 + n), "From tower", src, "to tower", dst
        post = Hanoi(n - 1, tmp, dst, src)
        return pre + post + 1
    else:
        return 1

请注意,这计算的是Hanoi函数的调用次数,而不是实际玩游戏时实际需要进行的移动次数.如果需要移动的数量,只需将基本情况下的return 1(最后一行)更改为return 0.

Note that this counts the number of calls to the Hanoi function, not the number of moves that actually need to be made if you were physically playing the game. If you want the number of moves, just change the return 1 in the base case (the last line) to return 0.

这篇关于河内带有“柜台"的塔楼在python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆