开发者

Get a number in an unordered straight that follow a start value from an interval

开发者 https://www.devze.com 2023-01-29 17:27 出处:网络
I search a fast method to perform my problem. imagine ordered seats numeroted from 1 to 8, imagine they are people on seats [ 2, 6, 5, 3 ]. i want to get back the second (interval +2) people after th

I search a fast method to perform my problem.

imagine ordered seats numeroted from 1 to 8, imagine they are people on seats [ 2, 6, 5, 3 ]. i want to get back the second (interval +2) people after the seat number 4 (start value)

for examples :

with this array : [2, 5, 8, 7, 1] , i started with value 3 and i move +2 times, the third next number in the list is 5, the second is 7, the method must return this value

with the sam开发者_Python百科e [2, 5, 8, 7, 1] , i started from 7 and i move +3 times here the method must return to the minimal value. trought 8.. 1.. 2.., result : 2

with [1, 3], start 4, count +2, result 3

with [5, 3, 9], start 3, count +1, result 5

with [5, 3, 9], start 3, count +2, result 9

I hope someone will understand my problem. thanks you


Sort your list, use bisect to find the starting index, then mod the result of the addition by the length of the list.


So, this is basically just an example implementation of Ignacio's algorithm in Python:

from bisect import bisect

def circular_highest(lst, start, move):
    slst = sorted(lst)
    return slst[(bisect(slst, start) - 1 + move) % len(lst)]

print circular_highest([2, 5, 8, 7, 1], 3, 2)
print circular_highest([2, 5, 8, 7, 1], 7, 3)
print circular_highest([1, 3], 4, 2)
print circular_highest([5, 3, 9], 3, 1)
print circular_highest([5, 3, 9], 3, 2)

Output:

7
2
3
5
9
0

精彩评论

暂无评论...
验证码 换一张
取 消