Reputation:
I am trying to write a simple python script that will find all the non-decreasing sequences made up of positive integers summing to 7. My code does not seem to work as it's supposed to no matter what I try. Here's what I have
components = [1,2,3,4,5,6,7]
ans = []
def sumSeq(seq):
sumA = 0
for i in seq:
sumA += i
return sumA
def findSeq(seq):
for x in components:
if (x < seq[-1]):
continue
newSeq = seq
newSeq.append(x)
sumA = sumSeq(newSeq)
if (sumA > 7):
continue
if (sumA == 7):
ans.append(newSeq)
findSeq(newSeq)
findSeq([0])
print ans
Upvotes: 0
Views: 307
Reputation: 352
When you do the following assignment:
newSeq = seq
you actually bind a different name (newSeq) to the same object (seq), you do not create a new object with similar values. So as you change the contents of newSeq, you change the contents of seq, too, since they are both aliases of the same object stored in memory. As the Python documentation says:
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.
So you have to change this line of code with:
newSeq = seq.copy()
Upvotes: 1
Reputation: 168716
newSeq = seq
This line doesn't do what you think it does. Specifically, it does not create a new list. It merely creates a new name that refers to the existing list. Try:
newSeq = seq[:]
Upvotes: 1