递归函数在我告诉它返回后仍在运行

问题描述 投票:0回答:1

我具有此功能,它可以递归检查并返回排列列表,但是即使我告诉它返回,它仍在运行吗?我觉得我可能缺少明显的东西。 (也在python 3中)

def createperm(ran: int, numints: int):
    acceptlsts = []

    def recursivechecker(lst):
        try:
            print("start")
            if lst == []:
                print(acceptlsts)
                lst == []
                return acceptlsts
            print("done checking if done")
            lst[-1] = lst[-1] + 1
            print("iterated last digit, %s is now %s" % (lst[:-1] + [lst[-1] -1] , lst))
            while lst[-1] in lst[:-1] or lst[-1] >= ran + 1:
                if lst[-1] >= ran + 1:
                    print("this number exceeds limits, going back")
                    lst = lst[:-1]
                    recursivechecker(lst)
                else:
                    print("this number isn't valid, trying next")
                    lst[-1] = lst[-1] + 1
            if len(lst) == numints:
                print("this solution is good, adding %s" % lst)
                templst = lst + []
                acceptlsts.append(templst)
                recursivechecker(lst)
            print("not long enough, adding dummy and testing that number")
            lst = lst + [0]
            print(lst)
            recursivechecker(lst)
        except IndexError:
            print("hi")
            return acceptlsts

    x = recursivechecker([0])
    print("yay", x)

createperm(5, 3)
python python-3.x recursion permutation
1个回答
0
投票

您的弱点是您使用自由变量acceptlsts来收集结果,而不是简单地处理recursivechecker()返回的内容。我花了一段时间才弄清楚您的代码要做什么,我希望我没错:

def createperm(ran, numints):

    def recursivechecker(lst):

        if not lst:
            return []

        lst[-1] += 1

        # iterate last digit
        while lst[-1] > ran or lst[-1] in lst[:-1]:
            if lst[-1] > ran:
                #  this number exceeds limits, going back
                return recursivechecker(lst[:-1])

            # this number isn't valid, trying next
            lst[-1] += 1

        if len(lst) == numints:
            # this solution is good
            return [lst] + recursivechecker(list(lst))  # use a copy of lst

        # not long enough, adding dummy and testing that number
        return recursivechecker(lst + [0])

    return recursivechecker([0])

用法

>>> createperm(5, 2)
[[1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2],
[3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4]]
>>> 

我想你已经很近了,但是需要退后一步,清理代码并正确处理所有事情。

© www.soinside.com 2019 - 2024. All rights reserved.