Manoj
Manoj

Reputation: 971

Better way to find if a number is present in between two numbers of a sorted list

I have a sorted list like this

s = [1 , 4 ,6 , 9  ,10 ]

I want to know if either a number is present in the list or if it is present in between two numbers. If it is present in between two numbers, I want to print them out.

Right now my code looks like this

for x in s:
   if b == x: \\ b is the number
       print b
   elif b > x and b < s[s.index(x) + 1] and s.index(x) < len(s):
       print b , s[s.index(x) + 1]

Is there a better way to do so?

Upvotes: 3

Views: 583

Answers (2)

georg
georg

Reputation: 214949

bisect module does exactly that:

s = [1 , 4 ,6 , 9  ,10 ]
import bisect

x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
    print x, 'is in the list'
else:
    print x, 'comes between', s[n-1:n], 'and', s[n:n+1]

Upvotes: 7

Vivek S
Vivek S

Reputation: 5540

This is not perfect optimized, but you can avoid using index() method many times!

for i,j in enumerate(s,1):
 if b == j: \\ b is the number
   print b
 elif b > j and b < s[i+1] and s[i] < len(s):
   print b , s[i + 1]

Upvotes: 0

Related Questions