Advisory: This web-page is a sketch full of mistakes I don't have time to correct. If you are looking for something comfortable to read I recommend you to move on to another page.
Here is an example of how to generate all the permutations of the characters of a string without the use of recursion:
cadena='string'
def permuta(cadena):
return reduce(lambda result, x:
[elem[:i] + x + elem[i:] for elem in result for i in range(len(elem)+1)],
cadena,
[''])
print permuta(cadena)
# Lo mismo ahorrando caracteres:
p=lambda c:reduce(lambda r,x:[e[:i]+x+e[i:] for e in r for i in range(len(e)+1)],c,[""])
# (That is what I call a powerful one-liner for string permutations)
print p(cadena)
# Ahora sin reduce y sin lambda:
def permuta5(c):
w=['']
[[w.append(e[:i]+v+e[i:]) for e in w[:] for i in range(len(e)+1)] for v in c]
u=[1]
[[u.insert(0,i*u[0]) or u.pop()] for i in range(1,len(c)+1)]
return w[len(w)-u[0]:]
print permuta5(cadena)
def permuta6(c):
w=['']
for v in c:
for e in w[:]:
for i in range(len(e)+1):
w.append(e[:i]+v+e[i:])
u=[1]
for i in range (1, len(c)+1):
u.insert(0,i*u[0]) or u.pop()
w = w[len(w)-u[0]:]
return w
#list(set(permuta6("palabra")))
Remember that 'reduce' has been removed in the latest versions of Python.