Compute all the Permutation of the String with Python

Configurare noua (How To)

Situatie

Recursion is used to find the permutations of a string yup.

  • The if condition prints string passed as argument if it is equal to the length of yub.
  • In each iteration of the for loop, each character of yup is stored in words.
  • The elements of words are swapped. In this way, we achieve all different combinations of characters.

Backup

Using recursion

def get_permutation(string, i=0):

    if i == len(string):   	 
        print("".join(string))

    for j in range(i, len(string)):

        words = [c for c in string]
   
        # swap
        words[i], words[j] = words[j], words[i]
   	 
        get_permutation(words, i + 1)

print(get_permutation('yup'))

Output

yup
ypu
uyp
upy
puy
pyu
None

Solutie

Tip solutie

Permanent

Voteaza

(2 din 4 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?