Wednesday, March 1, 2017

Damn you, permutations

I had such a hard time figuring out how to write a python function to generate permutations two weeks ago.

Then yesterday, I tried doing it again using a different method and I got stuck for half an hour. It finally worked when I used list.extend instead of list.append.

And then when I looked at the code I wrote two weeks ago, they were the exact same. Recursion within a for-loop. Damn. This site very helpfully explained the thinking: http://typeocaml.com/2015/05/05/permutation/


def permutate(input):
if len(input)==0:
return [[]]
output=[]
for index,num in enumerate(input):
remain=input[:index]+input[index+1:]
to_add=[[num]+ result for result in permutate(remain)]
output.extend(to_add)
print(output)
return output

print(permutate([1,2,3]))