Categories: Algorithmpython

String Permutation in Python

Problem

Given a string, write a function that uses recursion to output a list of all the possible permutations of that string.

For example, given s=’abc’ the function should return [‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’]

Note: If a character is repeated, treat each occurence as distinct, for example an input of ‘xxx’ would return a list with 6 “versions” of ‘xxx’

Solution

Let’s think about what the steps we need to take here are:

def permute(s):
    output = []
    
    if len(s) <= 1:
        output=[s]
    else:
        for i, let in enumerate(s):
            for perm in permute(s[:i]+s[i+1:]):
                output+=[let+perm]
    return output
permute('abc')

Test Your Solution

"""
RUN THIS CELL TO TEST YOUR SOLUTION.
"""

from nose.tools import assert_equal

class TestPerm(object):
    
    def test(self,solution):
        
        assert_equal(sorted(solution('abc')),sorted(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']))
        assert_equal(sorted(solution('dog')),sorted(['dog', 'dgo', 'odg', 'ogd', 'gdo', 'god']))
        
        print ('All test cases passed.')
        


# Run Tests
t = TestPerm()
t.test(permute)

All test cases passed.

Recommended: Introduction to Recursion

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Share
Published by
Hassan Raza

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 month ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

2 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 months ago