I want to check if a value exists in between two numbers in a sorted list and print what two numbers it exists between. For example, if the list is [1, 4, 8, 12, 16, 20]
and I want to see what two numbers the number 3
is between, 1
and 4
should be printed out. Is there any way to do this in python preferably without importing a module?
CodePudding user response:
If the list is sorted, you could use bisect.bisect:
import bisect
lst = [1, 4, 8, 12, 16, 20]
i = bisect.bisect(lst, 3)
print(lst[i - 1], lst[i])
Output
1 4
UPDATE
Without importing a module use:
lst = [1, 4, 8, 12, 16, 20]
i = next(j for j, e in enumerate(lst) if e >= 3)
print(lst[i - 1], lst[i])
Output
1 4
Note that the time complexity of the second approach is O(n) vs O(logn) of bisect
. As an alternative you could implement bisect, in the end is just binary search.
CodePudding user response:
I am not sure if there is a inbuilt function for this but you can check it very easily by iterating over the list and take a variable as input which you want to compare. If list is not sorted in that case may be you can sort the list first.
CodePudding user response:
I was going to suggest using range()
You can have list like so:
list = [1, 4, 5, 15, 22]
is_in_range = 3 in range(list[0], list[1]) # or any other element of the list - you can even iterate over this
print(is_in_range)
Not the best solution but works.