Skip to content

Instantly share code, notes, and snippets.

@flutesa
Created December 9, 2013 16:25
Show Gist options
  • Save flutesa/7875118 to your computer and use it in GitHub Desktop.
Save flutesa/7875118 to your computer and use it in GitHub Desktop.
from random import *
def find_first(array, element): #[l, r) first entry element
l = -1
r = len(array)
while l + 1 < r:
m = (l + r)//2
if array[m] >= element:
r = m
else:
l = m
return r # return array[r] - if need element, not index
def find_last(array, element): #(l, r] last entry element
l = 0
r = len(array)
while l + 1 < r:
m = (l + r)//2
if array[m] > element:
r = m
else:
l = m
return l # return array[l] - if need element, not index
#a = [1, 2, 2, 3, 4, 5]
a = [randint(1, 4) for i in range(10)]
a.sort()
print(a)
print("index of first \"2\" in array:", find_first(a, 2))
print("index of last \"2\" in array:", find_last(a, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment