Home > front end >  Find all permutations possible of a string but of all possible lengths
Find all permutations possible of a string but of all possible lengths

Time:06-17

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????

CodePudding user response:

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']

CodePudding user response:

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']
  • Related