0

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

2

2 Answers 2

1

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),
    ]
Sign up to request clarification or add additional context in comments.

Comments

0

No need to reinvent the weel:

from itertools import permutations

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.