I am writing a permutation function that generate all permutations of a list in Python. My question is why this works:
def permute(inputData, outputSoFar):
for elem in inputData:
if elem not in outputSoFar:
outputSoFar.append(elem)
if len(outputSoFar) == len(inputData):
print outputSoFar
else:
permute(inputData, outputSoFar) # --- Recursion
outputSoFar.pop()
permute([1,2,3],[])
But this does not:
def permute(inputData, outputSoFar):
for elem in inputData:
if elem not in outputSoFar:
outputSoFar.append(elem)
if len(outputSoFar) == len(inputData):
yield outputSoFar
else:
permute(inputData, outputSoFar) # --- Recursion
outputSoFar.pop()
for i in permute([1,2,3], []):
print i
This does not work either (yield a copy of the list):
def permute(inputData, outputSoFar):
for elem in inputData:
if elem not in outputSoFar:
outputSoFar.append(elem)
if len(outputSoFar) == len(inputData):
yield outputSoFar[:] # --- Copy of the list
else:
permute(inputData, outputSoFar) # --- Recursion
outputSoFar.pop()
for i in permute([1,2,3], []):
print i