Advertisements

How to permutate a string in Python 3

To permutate a string is to change the order or arrangement of the characters that the string is made up of. Given that n is the number of characters, there are n! different ways to permutate a given string.

This post shows how we can permutate a string in Python 3.

Without importing any Python 3 libraries

Printing different permutation of string with duplicates

def permutate_string(string, prefix = ''):
    if len(string) == 0:
        print(prefix)
    else:
        for i in range(len(string)):
            rem = string[0:i] + string[i+1:]
            permutate_string(rem, prefix + string[i])

permutate_string('abb')

''' Output:
abb
abb
bab
bba
bab
bba
'''

Collecting different permutation of string with duplicates in a list

def build_permutation_list(string, prefix='', permutation_list=[]):
    if len(string) == 0:
        permutation_list.append(prefix)
    else:
        for i in range(len(string)):
            rem = string[0:i] + string[i + 1:]
            build_permutation_list(rem, prefix + string[i], permutation_list)

permutation_list = []
build_permutation_list('abb', permutation_list=permutation_list)
# permutation_list will contain the list of string variations from this point on

Collecting different permutation of string without duplicates in a list

permutation_list = []
build_permutation_list('abb', permutation_list=permutation_list)
permutation_list = set(permutation_list)

With itertools.permutations library function

Printing different permutation of string with duplicates

from itertools import permutations

string_permutations = permutations('abb')
for string in string_permutations:
    print(''.join(string))
    
''' Output:
abb
abb
bab
bba
bab
bba
'''

Printing different permutation of string without duplicates

from itertools import permutations

# Use the set function to remove duplicates
string_permutations = set(permutations('abb'))
for string in string_permutations:
    print(''.join(string))

''' Output:
bba
bab
abb
'''
Advertisements

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Techcoil Recommends

Udemy.com Homepage 300x250
Advertisements
Advertisements