Python : Finding permutations and combinations of a string

We can use python itertools module to get permutations and combinations of a string as given below

import itertools
import unittest

def find_permutations(word):
	''' Join the list returned by permutations module to form a word
	and using set to remove duplicates'''
	return list(set([''.join(w) for w in itertools.permutations(word,len(word))]))
	
def find_combinations(word):
	''' Loop to get combinations of different size.
	Join the list returned by combinations module to form a word
	and using set to remove duplicates.
	Add these values to the list 'all_combinations' '''
	all_combinations=[]
	for i in range(len(word)):		
		all_combinations.extend(set([''.join(w) for w in itertools.combinations(word,i+1)]))
	return all_combinations

class Per_Comb_Test(unittest.TestCase):
	''' Using word 'caar' so that I can test
	for duplicates '''
    def test_find_permutations(self):
        self.assertEqual(find_permutations("caar"), ['aarc', 'arca', 'raac', 'arac', 'rcaa', 'acra', 'acar', 'raca', 'aacr', 'cara', 'caar', 'craa'])
    def test_find_combinations(self):
        self.assertEqual(find_combinations("caar"), ['a', 'c', 'r', 'aa', 'cr', 'ca', 'ar', 'car', 'caa', 'aar', 'caar'])
        
        
if __name__ == '__main__':
    unittest.main()        

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s