Home > OS >  Is there a way of getting the permutations of a string without using loops and list comprehension in
Is there a way of getting the permutations of a string without using loops and list comprehension in

Time:12-09

Is there a way of doing the above without using loops and list comprehension - Just recursion?

This is my solution with for loops:

def permutations(s):        
    if(len(s)==1):
        return [s]
    combs = []
    for i in range(len(s)):
        for perm in permutations(s[:i] s[i 1:]):
            combs  = [s[i] perm]
    return combs

example:

input :"bca"

output: ["abc", "acb", "bca", "bac", "cab", "cba"]

CodePudding user response:

Basically you move the end-conditions of your loop to an end-condition in the recursion. You can also pass the intermediary result down the chain to avoid for loops appending data to results.

def permutations(s, i=0, curr=""):
    # end what was the for loop
    if i == len(s):
        return []
    if len(s) == 1:
        return [curr   s]
    return [
        *permutations(s[:i]   s[i 1:], 0, curr   s[i]),
        *permutations(s, i 1, curr),
    ]

CodePudding user response:

No need to reinvent the weel:

from itertools import permutations

combs = [ ''.join(p) for p in permutations(s) ]
  • Related