gpt4 book ai didi

python - 在for循环中递归运行for循环(python)

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:50 26 4
gpt4 key购买 nike

我是Python新手,并且有尝试用它来解决电视节目倒计时中的数字游戏的想法。 (rules for those unfamiliar)。我用谷歌搜索,结果是this has been done before - 但我没有正确理解代码,然后想为什么不自己尝试一下。我已经搜索过,还有其他人在寻找递归解决方案,但我无法让他们为我的示例工作(抱歉,毕竟我对此很陌生)。

我想做的是获取一个数字列表,然后循环对它们进行操作,并将该对替换为输出。这将递归地重复,直到我们找到我们正在寻找的数字,或者数字列表减小到大小 1。

我的函数“single_move_generator”是一个生成元组的生成器((a,b,操作),答案,剩余使用的数字)。我想将元组的最后一部分作为新列表返回到函数中,但也要跟踪第一部分,因为它是我们如何实现答案的“历史”。目前我有以下内容:

target = 155
numbers_to_use = [6, 25, 3, 2]
for a in single_move_generator(numbers):
if a[1] == target:
print(a[0])
for b in single_move_generator(a[2]):
if b[1] == target:
print(a[0],b[0])
quit()
for c in single_move_generator(b[2]):
if c[1] == target:
print(a[0],b[0],c[0])
quit()

产生:

(25, 6, 'add') (3, 2, 'add') (31, 5, 'multiply')

但我希望能够给它一个更大的数字列表,并让它继续下去,直到列表达到大小一。我怀疑我需要一个 while 循环 - 但这种尝试不起作用。它不会找到目标或跟踪移动历史。

numbers_available = numbers
while len(numbers_available) >1 and target not in numbers_available:

for a in single_move_generator(numbers_available):
if a[1] == target:
print("Target Found", a)
break

numbers_available = a[2]

numbers_available = a[2]

我觉得必须有一种Python式的方法来做到这一点,这比我所做的要简洁得多 - 任何提示将不胜感激。谢谢!

最佳答案

根据您使用元组(i,j,操作)的想法,我编写了以下内容。这是一个递归解决方案,因为主函数会回调自身。

from itertools import combinations, product

def check_operation(i, j, operation):
"""
Check whether 'i operation j' is permitted.
"""
if operation == '/' and j == 0:
return False
elif operation == '/' and i%j != 0:
return False
# if not playing with negative values
#elif operation == '-' and i-j < 0:
# return False
else:
return True

def countdown(target, numbers, trackback):
if target in numbers:
print trackback
for possibility in product(combinations(numbers,2), ['+', '*', '/', '-']):
new_numbers = [k for k in numbers] # copy list, use list.copy in python 3
i, j = possibility[0][0], possibility[0][1]
operation = possibility[1]
new_numbers.remove(i)
new_numbers.remove(j)
if not check_operation(i, j, operation):
continue
new_numbers.append(eval('%i%s%i' % (i, operation, j)))
countdown(target, new_numbers, trackback+[possibility])

countdown(155, [6, 25, 3, 2], [])

它仅在存在解决方案的情况下才有效,因为它不会打算尽可能接近解决方案。但是,它将返回所有解决方案,而不仅仅是一个。

关于python - 在for循环中递归运行for循环(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36317233/

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