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?
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]
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With