Reputation: 7586
I'm trying to loop through an array, compute some values and store them in another array (output
). However, what I tried (see bellow) always prints the last value in the inarray
and the last computed sum
(not the max value, as intended) and the output
array also only contains the last value. I figured the output.append(sum)
should append the sum
value each time throughout the loop, but it doesn't. If I print the sum values directly though, it shows on the console. What am I doing wrong?
def discountCombinations(inarray):
for i in range(len(inarray)):
max = 0
maxi = 0
output = list()
...
#do stuff
...
sum = new_y.sum()
output.append(sum)
print sum
if sum > max:
max = copy.copy(sum)
maxi = copy.copy(i)
print (max,": ", inarray[maxi])
print output
Upvotes: 0
Views: 57
Reputation: 46
In each iteration you are re-initializing the variable "output" as an empty list in this line: "output = list()". You just need to move this line before "for" loop.
Upvotes: 1
Reputation: 78842
You're resetting max, maxi, and output for every input item you process. You should only do this once, before processing any input items, for example:
max = 0
maxi = 0
output = list()
for i in range(len(inarray)):
...
#do stuff
...
Upvotes: 3
Reputation: 78564
output = list()
is defined in the for loop, so the result of the previous append is destroyed at the next iteration of the loop. Your max
and maxi
values are equally defined in the loop, and the same thing follows.
Upvotes: 5