Change language

Python | Ways to find all permutation of a string

| |

Method # 1: Using the naive method

# Python code for demo
# find all permutations
# given string

 
# Initializing string

ini_str = "abc"

 
# Print start line

print ( "Initial string" , ini_str)

 
# Find all permutations

result = []

 

def permute (data, i, length): 

if i = = length: 

result.append (’’ .join (data))

else

for j in range (i, length): 

# exchange

data [i], data [j] =   data [j], data [i] 

permute (data, i + 1 , length) 

data [i], data [j] = data [j], data [i] 

permute ( list (ini_str), 0 , len (ini_str))

 
# Print result

print ( "Resultant permutations" , str (result))

Exit :

 Initial string abc Resultant permutations [’abc’,’ acb’, ’bac’,’ bca’, ’cba’,’ cab’] 

Method # 2: Using itertools

# Python code for demo
# find all permutations
# given string

 

from itertools import permutations

 
# Initializing string

ini_str = "abc"

 
# Print start line

print ( " Initial string " , ini_str)

 
# Find all permutations

permutation = [’’ .join (p) for p in permutations (ini_str)]

# Print result

print ( "Resultant List" , str (permutation))

Output:

 Initial string abc Resultant List [’abc’,’ acb’, ’bac’,’ bca’, ’cab’,’ cba’]