Created
October 12, 2018 16:23
-
-
Save ysinjab/7e1a16d05ec6a82f528bf7f809f9a18b to your computer and use it in GitHub Desktop.
This file contains 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 | |
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