Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在for循环中递归运行for循环(python)_Python_Loops_For Loop_Recursion - Fatal编程技术网

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

在for循环中递归运行for循环(python),python,loops,for-loop,recursion,Python,Loops,For Loop,Recursion,我是python新手,有一个想法,就是尝试用它来解决电视节目倒计时中的数字游戏。(). 我在谷歌上搜索了一下,结果发现——但我没有正确理解代码,然后想,为什么不自己试一试呢。我已经搜索过了,还有其他人在寻找递归解决方案,但我无法让他们为我的示例工作(抱歉,毕竟我对这一点非常陌生) 我试图做的是获取一个数字列表,然后循环应用对它们的操作,并用输出替换该对。这将递归地重复,直到我们找到要查找的数字,或者数字列表缩小到1 我的函数“single_move_generator”是一个生成元组的生成器,元

我是python新手,有一个想法,就是尝试用它来解决电视节目倒计时中的数字游戏。(). 我在谷歌上搜索了一下,结果发现——但我没有正确理解代码,然后想,为什么不自己试一试呢。我已经搜索过了,还有其他人在寻找递归解决方案,但我无法让他们为我的示例工作(抱歉,毕竟我对这一点非常陌生)

我试图做的是获取一个数字列表,然后循环应用对它们的操作,并用输出替换该对。这将递归地重复,直到我们找到要查找的数字,或者数字列表缩小到1

我的函数“single_move_generator”是一个生成元组的生成器,元组的形式是((a,b,operation),答案,剩下的数字。我想将元组的最后一部分作为新列表反馈到函数中,但也要跟踪第一部分,因为它是我们如何获得答案的“历史”。目前,我有以下几点:

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]

我觉得一定有一种蟒蛇式的方法来做这件事,它比我做的要整洁得多——任何提示都将不胜感激。谢谢

基于您使用元组
(i,j,operation)
的想法,我写了以下内容。这是一个递归解决方案,因为主函数会调用自己

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], [])
来自itertools导入组合,产品
def检查_操作(i、j、操作):
"""
检查是否允许“i操作j”。
"""
如果操作=='/'和j==0:
返回错误
elif操作=='/'和i%j!=0:
返回错误
#如果不玩负值
#elif运算=='-'且i-j<0:
#返回错误
其他:
返回真值
def倒计时(目标、数字、回溯):
如果目标数量为:
打印回溯
对于乘积中的可能性(组合(数字,2),['+','*','/','-']):
new_numbers=[k代表数字中的k]#复制列表,在python 3中使用list.copy
i、 j=可能性[0][0],可能性[0][1]
操作=可能性[1]
新的_编号。删除(i)
新的_编号。删除(j)
如果不检查_操作(i,j,操作):
持续
new_numbers.append(eval(“%i%s%i%”(i,operation,j)))
倒计时(目标、新编号、回溯+[可能性])
倒计时(155,[6,25,3,2],]

它只在解决方案存在时起作用,因为它不打算尽可能接近解决方案。但是,它将返回所有解决方案,而不仅仅是一个。

根据您发布的内容,这应该适用于您:

def solve(numbers, target):
  for op, res, nums in single_move_generator(numbers):
    if res == target:
      return [op]
    ops = solve(nums, target)
    if ops:
      return [op] + ops

print(*solve(numbers_to_use, target))
它应该相当于您发布的嵌套for循环


res==target
时,将到达递归的底部。默认情况下,Python函数返回
None
,因此如果对
solve
的递归调用返回了一个truthy值,那么它一定达到了目标
ops
将包含最后一个操作(如果它是递归的底部)。然后将其附加到启动递归调用并返回到上层的操作。因此,该函数将返回顶层的所有操作。

我在您的代码中没有发现任何递归操作。另一个循环下的循环称为“嵌套循环”。那么递归是什么呢?我可能误解了。我承认我发布的是一个嵌套循环,但我想永远继续嵌套(或者说直到达到某个点,但不知道需要多少个循环),然后回溯适合您。谷歌吧,谢谢!Itertools看起来很有用,所以我会详细阅读。这是对我的代码的一次更干净的重写,为思考如何更好地处理它提供了很好的素材。感谢您的输入:)这是我遇到的问题的解决方案-谢谢!我没有意识到(或想检查)函数可以调用它们自己。谢谢你的帮助input@Steve来回答你上面的问题。这(一个调用自身的函数)通常被理解为递归,MASh说他没有发现。