简体   繁体   中英

Clean way to append to a list in a recursive function

When finding permutations for a list like this:

def permut(nums: List[int]) -> List[List[int]]:
    result = []

    def perm(a, k=0):
        if k == len(a):
            result.append(a)
        else:
            for i in range(k, len(a)):
                a[k], a[i] = a[i], a[k]
                perm(a, k + 1)
                a[k], a[i] = a[i], a[k]

    perm(nums)
    return result

this doesn't work because I'm overwriting a each time and result is just a list of items all pointing to a

I can change that line to be like:

result.append([item for item in a])

But that seems just like a hack to create a new list from a. What is a better way to deal with append to list in recursive functions?

A better recursive approach is to avoid managing the item swapping back-and-forth yourself and instead rely on the call stack to do that for you:

def perm(lst):
    if lst:
        for index, item in enumerate(lst):
            for p in perm(lst[:index] + lst[index + 1:]):
                yield [item, *p]
    else:
        yield []

so that:

for p in perm([1, 2, 3]):
    print(p)

outputs:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM