gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:15:27 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com