i have a function in python, which is programmed recursive in a list comprehension. But i don't understand it clearly what really happens in it!
def permut(s,l):
if l == []: return [[s]]
return [ e + [l[0]] for e in permut(s, l[1:])] + [l+[s]]
The function gets two arguments, firstly a String and the second a list and it returns the permutation of the String in the list.
permut('a', [1,2,3])
[['a', 3, 2, 1], [3, 'a', 2, 1], [2, 3, 'a', 1], [1, 2, 3, 'a']]
Can someone explain, what happens in the list comprehension?
If the list comprehension syntax is throwing you off, you can rewrite this function as follows and add some debug print()s along the way:
def permut(s,l):
print("Entering function permut()")
print("Parameters:\ns: {}\nl: {}".format(s,l))
if l == []:
print("End of recursion reached, returning {}".format([[s]]))
return [[s]]
result = []
for e in permut(s, l[1:]):
result.append(e + [l[0]])
result += [l + [s]]
print("Returning {}".format(result))
return result
This is the output you get:
>>> permut('a', [1,2,3])
Entering function permut()
Parameters:
s: a
l: [1, 2, 3]
Entering function permut()
Parameters:
s: a
l: [2, 3]
Entering function permut()
Parameters:
s: a
l: [3]
Entering function permut()
Parameters:
s: a
l: []
End of recursion reached, returning [['a']]
Returning [['a', 3], [3, 'a']]
Returning [['a', 3, 2], [3, 'a', 2], [2, 3, 'a']]
Returning [['a', 3, 2, 1], [3, 'a', 2, 1], [2, 3, 'a', 1], [1, 2, 3, 'a']]
[['a', 3, 2, 1], [3, 'a', 2, 1], [2, 3, 'a', 1], [1, 2, 3, 'a']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With