I have a Python list of predefined integers:
intvals = [5000, 7500, 10000, 20000, 30000, 40000, 50000]
I need to round down and up to the next lower/higher value in the list. So for example, given the number 8000, the result should be [7500, 10000]. For 42000, it should be [40000, 50000]. I am wondering if there is an easy way to do it.
My idea would be to create a function that has two loops – one that decreases a value -1 until it finds one in the list, and one that increases the value by 1 until it finds the higher match. This would work but maybe there is a better solution?
This is perfect for bisect.bisect_right() and bisect.bisect_left().
Here is some example code for which you can expand on:
This technique is fast as it uses binary search (so logN instead of N lookups)