3

I was trying to create a code to display all possible permutations of a string without using itertools, so I came up with a basic idea of how I could get this to work using these ugly nested for-loops but now I want to convert this into a function for any string with length 'n', I'm kinda new to recursion so I need some help sorting this out.

wrdinp=input("Enter a word: ")
d=[]
#Works for string with length 4
for a in wrdinp:
    for b in wrdinp:
        if b!=a:
            for c in wrdinp:
                if c!=a and c!=b:
                    for d in wrdinp:
                        if d!=a and d!=b and d!=c:
                            d.append(a+b+c+d)
print("Permutations:",d)

I need a function that takes in a string of any length and returns a list that contains the various permutations of the string.

1
  • You can find a solution via Google without much difficulty: geeksforgeeks.org/…. You only need to convert the string to a list to apply the algorithm. Commented Aug 10, 2019 at 12:21

1 Answer 1

3

This is a way to do it in recursion:

def permutations(wrdinp):
    if len(wrdinp) <= 1:
       return [wrdinp]
    else:
       d = []
       for e in permutations(wrdinp[:-1]):
           for i in range(len(e)+1):
               d.append(e[:i] + wrdinp[-1] + e[i:])
       return d
wrdinp=input("Enter a word: ")
result = permutations(wrdinp)
print(result)

Hope it helps :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, it helped! My first day here on Stack Overflow, already loving it due to people like you ready to help others :)
@PraneetR really happy it helped you. You can also repay it back by checking this answer as the best one when it is available, which should be available after a while. Hope you keep the request :)

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.