pookie
pookie

Reputation: 4142

Python circular range with center point and radius from list

Using Python 3.X, I have a list of numbers, with a maximum index of 2880. I want to choose an arbitrary index (eg 1500) and define a "radius" around that index of say, 5. So, I generate a range of indicies: 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505.

To do this, I'd use the following:

min = 0
max = 2880
center = 1500
radius = 5
r = range(center - radius, center + radius + 1)
>> 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505

The problem is, what if I define the center as 2878? I do not want 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 2881, 2882...

I need 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 0, 1, 2

Is there a built in function in Python 3, which allows accepts a center, radius and array to do this? Something like:

def GetBounds(listOfIntegers, centerIndex, radius):
    ...

Upvotes: 1

Views: 1398

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55479

You can easily create a generator to do this. You can use the generator just like range.

def bounded_range(center, radius, highest):
    mod = highest + 1
    for i in range(center - radius, center + radius + 1):
        yield i % mod

lst = []
for i in bounded_range(1500, 5, 2880):
    lst.append(i)

print(lst)
print(list(bounded_range(2878, 5, 2880)))

output

[1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505]
[2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 0, 1, 2]

BTW, you shouldn't use min or max as variable names because that shadows the built-in min and max functions.

Upvotes: 2

AugBar
AugBar

Reputation: 457

I would use a list comprehension to do the job. Something like:

r = [ i % (max + 1) for i in range(center - radius, center + radius + 1)]

>>> max = 2880
>>> center = 2878
>>> radius = 5
>>> [ i % (max + 1) for i in range(center - radius, center + radius + 1)]
[2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 0, 1, 2]

Upvotes: 8

Related Questions