如何将“ for循环”转换为“递归”?

时间:2020-08-18 15:29:37

标签: python for-loop recursion

我遵循了一个功能

下面的“列表”包含12个列表元素。

def calLen(lists):
    my_array = []
    count = 0
    for item0 in lists[0]:
        my_array.append(item0)
        for item1 in lists[1]:
            my_array.append(item1)
            for item2 in lists[2]:
                my_array.append(item2)
                for item3 in lists[3]:
                    my_array.append(item3)
                    for item4 in lists[4]:
                        my_array.append(item4)
                        for item5 in lists[5]:
                            my_array.append(item5)
                            for item6 in lists[6]:
                                my_array.append(item6)
                                for item7 in lists[7]:
                                    my_array.append(item7)
                                    for item8 in lists[8]:
                                        my_array.append(item8)
                                        for item9 in lists[9]:
                                            my_array.append(item9)
                                            for item10 in lists[10]:
                                                my_array.append(item10)
                                                for item11 in lists[11]:
                                                    my_array.append(item11)
                                                    my_set = set(my_array)
                                                    if len(my_set) > 7 :
                                                        count += 1
                                                    my_array.pop()
                                                my_array.pop()
                                            my_array.pop()
                                        my_array.pop()
                                    my_array.pop()
                                my_array.pop()
                            my_array.pop()
                        my_array.pop()
                    my_array.pop()
                my_array.pop()
            my_array.pop()
        my_array.pop()
    print(count)
    if count > 0 :
        return True
    else :
        return False

assert calLen([[0,1],[1],[2,3,4],[5],[1,4,7],[3,5],[6],[1,2,3,4],[5,6],[1,7],[2,5,7],[0,3,4]]) == True, "Error-1!"
assert calLen([[1,3],[2,7],[5],[6],[7],[2],[4,5],[2,3,4,5,6],[2,3,7],[1,4,5],[3],[6]]) == False, "Error-2!"

我知道...看起来很蠢!

幸运的是,这次“ n(列表的长度)”固定为12,但是如果n的值不同,如何将其更改为递归函数?


我要解决的问题。

有12个列表,每个列表的随机数范围为0到7,例如[0], [1,4,6], [6,7]

您只需从每个列表中获得一个数字,然后将它们全部放在一个集合中即可。

如果您可以设置{0,1,2,3,4,5,6,7},则返回True否则为False。

请参见assert示例。

2 个答案:

答案 0 :(得分:1)

这可以递归完成,但是有更好的方法。标准库具有执行此操作的功能:itertools.product(请参阅https://docs.python.org/3/library/itertools.html#itertools.product)。

import itertools

def calLen(lists):
    count = 0
    for my_array in itertools.product(*lists):
        my_set = set(my_array)
        if len(my_set) > 7:
            count += 1
    print(count)
    if count > 0:
        return True
    else:
        return False

也许是一个简单的示例,可以使它更清楚itertools.product的功能:

>>> for combination in itertools.product([1, 2], ['a', 'b', 'c']):
    print(combination)

    
(1, 'a')
(1, 'b')
(1, 'c')
(2, 'a')
(2, 'b')
(2, 'c')

答案 1 :(得分:1)

是的,这确实是一个最好可以使用递归解决的问题。您拥有更多控制权,可以在代码中进行正确的检查,并且仅遵循列表中可能具有正确答案的路径。将12个嵌套的for循环用于12个列表的乘积将不是一个有效的解决方案。

这是我的解决方案:

def find_range(end, lists):
    def find_range_inner(index, se):
        # Return false if there are more numbers that have to be found
        # then there are lists to be searched for.
        if len(lists) - index - 2 < end - len(se):
            return False
        # Found all the numbers. 
        if len(se) == end + 1:
            return True
        # Check the options and return if any of them is True.
        # `any` will make sure it won't continue searching if
        # it already has found a True.
        return any(
            find_range_inner(index + 1, se | {el})
            for el in lists[index]
            if el not in se
        )
    return find_range_inner(0, set())


if __name__ == '__main__':
    li = [
        [0, 2],
        [0, 1],
        [3]
    ]
    end = 3
    print(find_range(end, li))
    li.append([1, 2])
    print(find_range(end, li))

即使找到更多列表,它也会在找到解决方案的情况下尽早返回。另外,由于any如果在迭代中找到“任意” True,将直接停止进一步迭代,从而提高了效率。