Saimon Ghimire
Saimon Ghimire

Reputation: 1

Find all permutations possible of a string but of all possible lengths

getting simple permutations of a string is easy but how do you do if you want different length permutations For eg:

def permutations(string):
    if len(string) == 1:
        return [string]
    else:
        perms = []
        for i in range(len(string)):
            for perm in permutations(string[:i] + string[i+1:]):
                perms.append(string[i] + perm)
    return perms
permutations('abc')

returns ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

but i want ['abc', 'acb', 'bac', 'bca', 'cab', 'cba','ab','ba','bc','cb','ca','ac','a','b','c']

How do i get that extra arrangements????

Upvotes: 0

Views: 539

Answers (2)

VPfB
VPfB

Reputation: 17267

With just one line added:

def permutations(string):
    if len(string) == 1:
        return [string]
    else:   # note: else not needed after return
        perms = []
        for i in range(len(string)):
            for perm in permutations(string[:i] + string[i+1:]):
                perms.append(string[i] + perm)
            perms.append(string[i])  # <--- new line
    return perms

Output:

['abc', 'ab', 'acb', 'ac', 'a', 'bac', 'ba', 'bca', 'bc', 'b', 'cab', 'ca', 'cba', 'cb', 'c']

Upvotes: 0

Ohad Sharet
Ohad Sharet

Reputation: 1142

you should use permutations from itertools

from itertools import permutations
all_perm = []
st="abc"
for i in range(1,len(st)+1):
    all_perm += list(permutations(st,i))
    
all_perms_str = [''.join(str(e) for e in perm) for perm in all_perm]
print (all_perms_str)

output:

['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Upvotes: 1

Related Questions