Kemal Kemal - 5 months ago 9
Python Question

A loop for adding list element without high memory performance?

Everybody,

a =[0, 0, 2, 4, 6]

x=5

This a list (a) and a fix value (x).
I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words result should like below:

0
0
2
4
6
0
0
7
9
11
0
0
12
14
16
0
0
15
19
21
0
0
21
24
26


I prepared codes as below but it doesn’t work. Other words produce something as below (incorrect)

i=0
counter=0
while counter < x:
for i in a:
if i >0:
i=i+x
elif i ==0:
i=0
print i
counter=counter+1


0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11

So, I need to help for this…
Thank you.

Answer

I think this does mostly what you want (at least, as I understand the question)...

def make_it_so(a, x):
  i = 0
  counter=0
  while counter < x:
    for i in a:
      if i == 0:
        yield 0
      else:
        yield i + counter * x
    counter = counter + 1

# Demo
for item in make_it_so([0, 0, 2, 4, 6], 5):
    print item

Note that I've made it a generator function. You could easily turn it into a regular function that returns a list if you created an output list at the top of the function and swapped yield ... for output_list.append(...) and then return output_list at the end of the function...

The key here is to understand that after the first loop, you are adding 0 to all of the (non-zero) items. After the second loop, you are adding x. After the third loop, you're adding the x + x (since the first loop added x and now you're adding x more). In general, for the Nth loop, you'll be adding (N-1) * x to all of the non-zero items. So, you just need to keep track of N, (or N-1). In fact, your original code was already doing this (with counter), so we just re-purpose that and it's all good.

Comments