Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an alternating range?

Tags:

python

I need to search for an item in a list around a given index with in a given radius. Currently I use this function to generate alternating offsets for the search:

def generateSearchIndizes(radius):
    for i in range(1, radius + 1):
        yield i
        yield -i

The code that does the search looks something like this:

for i in generateSearchIndizes():
    if pred(myList[baseIndex + i]):
        result = myList[baseIndex + i]
        break # terminate search when first item is found

My question is, is there a more elegant way to generate the search indizes, maybe without defining a special function?

like image 889
Björn Pollex Avatar asked Dec 31 '10 12:12

Björn Pollex


2 Answers

is there a more elegant way to generate the search indices

I don't think there's a more elegant way. Your code is very simple and clear.

maybe without defining a special function?

Yes, that's definitely possible.

>>> [b for a in ((x,-x) for x in range(1, 10 + 1)) for b in a]
[1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8, 9, -9, 10, -10]
like image 109
Mark Byers Avatar answered Nov 07 '22 22:11

Mark Byers


Here's my go at it:

from itertools import chain

>>> list(chain(*zip(range(1, 7), range(-7, 0)[::-1])))
[1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6]

Adjust as needed. :)

like image 28
Juho Vepsäläinen Avatar answered Nov 07 '22 23:11

Juho Vepsäläinen