Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
for j in testGen(a,n-i-1):
yield j
My confusion is illustrated below.
>>> list(testGen([1,2],4))
yield [10, 2]
yield [10, 4]
yield [10, 7]
yield [12, 11]
yield [12, 13]
[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]
I can get the right answer simply by using a copy of the array (e.g. passing in a[:]
to the recursive call) but I still don't understand the above behavior.
Why are the print statements and yield values different?