I am trying to write a function in python. The function is based on a algorithm. It is summation using sides of polygons with n sides. For each "loop" you add n[i]+n[1+i]. In python can you do this with for loops? This is a very easy thing to do in languages like java and c++. But the nature of python for loops make it less obvious. Can for loops accomplish this or should while loops be use?
2 Answers
You can use zip and for-loop here:
>>> lis = range(10)
>>> [x+y for x, y in zip(lis, lis[1:])]
[1, 3, 5, 7, 9, 11, 13, 15, 17]
If the list is huge then you can use itertools.izip and iter:
from itertools import izip, tee
it1, it2 = tee(lis) #creates two iterators from the list(or any iterable)
next(it2) #drop the first item
print [x+y for x, y in izip(it1, it2)]
#[1, 3, 5, 7, 9, 11, 13, 15, 17]
Comments
for i in range(N): # i = 0,1, ... N-1
val = n[i] + n[i+1]
if you want to 'wrap around', you can write
for i in range(N): # i = 0,1, ... N-1
val = n[i] + n[(i+1)%N]
.. or use the fact that n[-1] is the same as the last element
for i in range(N): # i = 0,1, ... N-1
val = n[i-1] + n[i] # [N-1]+[0], [0]+[1], ... [N-2] + [N-1]
This approach will likely be slower but may be easier to follow than zips and iterations.