Algorithm


1. **Function Definition**
    - Define a function `permute` that takes the string and an optional index as parameters.
 
2. **Base Case**
    - If the index is equal to the length of the string minus 1, print the string (permuted).

3. **Permutation Logic**
    - Iterate through the characters starting from the index.
    - Swap the current character with the character at the index.
    - Recursively call the `permute` function with the updated string and the next index.

4. **Backtrack**
    - After each recursive call, swap the characters back to their original positions.

Code Examples

#1 Code Example- Python Program Using recursion

Code - Python Programming

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'))
Copy The Code & Try With Live Editor

Output

x
+
cmd
yup
ypu
uyp
upy
puy
pyu
None

#2 Code Example- Pyrhon Programing Using itertools

Code - Python Programming

from itertools import permutations

words = [''.join(p) for p in permutations('pro')]

print(words)
Copy The Code & Try With Live Editor

Output

x
+
cmd
['pro', 'por', 'rpo', 'rop', 'opr', 'orp']
Advertisements

Demonstration


Python Programing Example to Compute all the Permutation of the String-DevsEnv