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'],[''],[''])