Skip to content

Instantly share code, notes, and snippets.

@ysinjab
Created October 12, 2018 16:23
Show Gist options
  • Save ysinjab/7e1a16d05ec6a82f528bf7f809f9a18b to your computer and use it in GitHub Desktop.
Save ysinjab/7e1a16d05ec6a82f528bf7f809f9a18b to your computer and use it in GitHub Desktop.
import bisect
import random
def search_index(numbers, number):
i = bisect.bisect_left(numbers, number)
if i == len(numbers):
return i - 1
elif numbers[i] == number:
return i
elif i > 0:
j = i - 1
if numbers[i] - number > number - numbers[j]:
return j
return i
sorted_numbers = []
non_sorted_numbers = []
for i in xrange(400000):
bisect.insort(sorted_numbers, random.randint(0, 1000))
non_sorted_numbers.append(random.randint(0, 1000))
%timeit non_sorted_numbers.index(4)
# 100000 loops, best of 3: 12 µs per loop
%timeit search_index(sorted_numbers, 4)
# 1000000 loops, best of 3: 829 ns per loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment