Skip to main content

String Permutations

Problem Statement#

In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders.

Examples:

permutations('a'); # ['a']permutations('ab'); # ['ab', 'ba']permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']

The order of the permutations doesn't matter.

My Solution#

def permutations(string):    result, seen = list(), set()    permutation("", string, result, seen)
    return result
def permutation(prefix, string, result, seen):    n = len(string)
    if(n == 0):        result.append(prefix)    else:        for i in range(n):            branch = prefix+string[i]            if( branch not in seen):                seen.add(branch)                permutation(prefix + string[i], string[0:i] + string[i+1:n], result, seen)

Top Best Practices#

import itertools
def permutations(string):    return list("".join(p) for p in set(itertools.permutations(string)))

Top Clever#

def permutations(string):  if len(string) == 1: return set(string)  first = string[0]  rest = permutations(string[1:])  result = set()  for i in range(0, len(string)):    for p in rest:      result.add(p[0:i] + first + p[i:])  return result