Last active
December 5, 2017 18:23
-
-
Save pykong/56b114e0309a1337bc04703172e4c1b5 to your computer and use it in GitHub Desktop.
Gets both numbers adjacent to input number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bisect | |
def get_neighbours(num, interval): | |
interval = set(interval) | |
interval.discard(num) | |
interval = list(interval) | |
interval.sort() | |
if num < interval[0] or interval[-1] < num: | |
return interval[-1], interval[0] | |
else: | |
i = bisect.bisect_right(interval, num) | |
neighbours = interval[i-1:i+1] | |
return neighbours | |
### test input | |
l = [1, 3, 4, 8, 20, 33, 36, 68] | |
>>> get_neighbours(8, l) # element in l | |
4, 20 | |
>>> get_neighbours(55, l) # element not in l | |
36, 68 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment