简体   繁体   中英

Recursive list building: permutations of all lengths

I've been having some trouble with recursion, especially with lists. I don't understand the process of 'building a list recursively' very well, since I don't really get where the lists are created. I have gotten this program to print out all the permutations of len(string) , but I would like to extend it so that it'll also give me the permutations of length 1 to len(string) - 1 . Here is what I have got:

def subset(string):
    result = []

    if len(string) == 0:
        result.append(string)
        return result
    else:
        for i in range(len(string)):
            shorterstring = string[ :i] + string[i+1: ]

            shortersets = subset(shorterstring)

            for s in shortersets:
                result.append(string[i] + s)
    return result

Which gives:

print(subset("rum"))
['rum', 'rmu', 'urm', 'umr', 'mru', 'mur']

I don't understand why that when I change result.append(string[i] + s) , to just result.append(s) , I get no output at all.

If you change result.append(string[i] + s) to result.append(s) , your code will only add permutations of length len(string) to results when len(string) == 0 .

For your code to generate all permutations, the last for loop needs to be:

for s in shortersets:
    result.append(string[i] + s)
    result.append(s) 

Note that when used with the original code, you will actually end up adding multiple instances of the same permutations to the final output. You could fix this by making results a set instead of a list , but you might want to try re-writing your code to avoid this inefficiency altogether.

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