0

How can I implement the recursive way to write the permutation of an string? For example, if the input is 'abc', I want my result to be:

[a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba',
 'bb','bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db',
 'dc','dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee', 'aaa', 'aab', 'aac',
 'aad','aae', 'aba', 'abb', 'abc', 'abd', 'abe', 'aca', 'acb',
 'acc'....]

In addition, if a string from the result is also contained in an another list, then return that string. For example 'a' and 'b' are in [a,aaah,aahed,aahing,aahs,'b'], I want to display the 'a' and 'b'.

Edit

I tried to use a for loop, but I get a MemoryError.

def perm(l,last,result)
    if len(result[-1]==len(l)):
        return result
    else:
        for i in l:
            for u in last:
                last.append(u+i)
         result.extend(last)
    perm(l,last,result)
    return result

perm(['a','b','c'],[''],[''])
dimo414
  • 47,227
  • 18
  • 148
  • 244
BlackS
  • 33
  • 3

1 Answers1

0

Generate all strings of the current length and then look for longer strings recursively.

def perm(chars, prefix):
    result = []
    if len(prefix) < len(chars):
        for char in chars:
            result.append(prefix + char)
        for char in chars:
            result.extend(perm(chars, prefix + char))
    return result

print perm(["a", "b", "c"], "")
dlask
  • 8,776
  • 1
  • 26
  • 30