Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting nested for-loops into a recursive function in Python

Tags:

python

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.

like image 598
Praneet R Avatar asked Mar 20 '26 02:03

Praneet R


1 Answers

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 :)

like image 187
Mahir Islam Avatar answered Mar 22 '26 15:03

Mahir Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!