python - 我怎样才能修复这个汉诺塔程序以获得我想要的输出?

标签 python python-3.x tuples

def moveTower(height,fromPole, toPole, withPole):
    if height >= 1:
        moveTower(height-1,fromPole,withPole,toPole)
        moveDisk(fromPole,toPole)
        moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):
    print("("+fp + "," +tp+')')


moveTower(4,"A","B","C") 

我需要输出为元组列表(例如:[('A','C'),('A','B'), ...])

当前输出:

(A,C)
(A,B)
(C,B)
(A,C)
(B,A)
(B,C)
(A,C)
(A,B)
(C,B)
(C,A)
(B,A)
(C,B)
(A,C)
(A,B)
(C,B)

最佳答案

您不应该打印这些元素。也许最优雅的方法是构造一个生成器:

def moveTower(height,fromPole, toPole, withPole):
    if height >= 1:
        <b>yield from</b> moveTower(height-1,fromPole,withPole,toPole)
        <b>yield (fromPole, toPole)</b>
        <b>yield from</b> moveTower(height-1,withPole,toPole,fromPole)

yield <expr>因此,这里发出由 <expr> 构造的值在发电机中,和 yield from <iterable>用于发出 <iterable> 中的所有元素作为该生成器的元素。

然后我们可以使用list(..)实现生成器:

>>> list(moveTower(2, *'ABC'))
[('A', 'C'), ('A', 'B'), ('C', 'B')]
>>> list(moveTower(3, *'ABC'))
[('A', 'B'), ('A', 'C'), ('B', 'C'), ('A', 'B'), ('C', 'A'), ('C', 'B'), ('A', 'B')]
>>> list(moveTower(4, *'ABC'))
[('A', 'C'), ('A', 'B'), ('C', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('A', 'C'), ('A', 'B'), ('C', 'B'), ('C', 'A'), ('B', 'A'), ('C', 'B'), ('A', 'C'), ('A', 'B'), ('C', 'B')]

关于python - 我怎样才能修复这个汉诺塔程序以获得我想要的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52874604/

相关文章:

python:字典到字典的元组

python - 在元组字典中搜索多个最小值

python - UnicodeDecodeError : 'charmap' codec can't decode byte 0x81 in position 49: character maps to <undefined>

python - 将字符串后置到文件名(使用 pathlib 路径)

python - 访问元组的元素

python - Django 中的 ForeignKey 形式限制

python - 为什么要继承主Tk窗口?

python - 从 dict 制作 Dataframe

python - 循环遍历 Excel 文件,查找某些单元格值并写入文本文件

python - 仅获取与 Django 查询集相关的模型