forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
count_elem.py
52 lines (48 loc) · 1.57 KB
/
count_elem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def count_elem(array, query):
def first_occurance(array, query):
lo, hi = 0, len(array) -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if (array[mid] == query and mid == 0) or \
(array[mid] == query and array[mid-1] < query):
return mid
elif (array[mid] <= query):
lo = mid + 1
else:
hi = mid - 1
def last_occurance(array, query):
lo, hi = 0, len(array) -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if (array[mid] == query and mid == len(array) - 1) or \
(array[mid] == query and array[mid+1] > query):
return mid
elif (array[mid] <= query):
lo = mid + 1
else:
hi = mid - 1
first = first_occurance(array, query)
last = last_occurance(array, query)
if first is None or last is None:
return None
return last - first + 1
array = [1,2,3,3,3,3,4,4,4,4,5,6,6,6]
print(array)
print("-----COUNT-----")
query = 3
print("count: ", query, " :" , count_elem(array, query))
print("-----COUNT-----")
query = 5
print("count: ", query, " :" , count_elem(array, query))
print("-----COUNT-----")
query = 7
print("count: ", query, " :" , count_elem(array, query))
print("-----COUNT-----")
query = 1
print("count: ", query, " :" , count_elem(array, query))
print("-----COUNT-----")
query = -1
print("count: ", query, " :" , count_elem(array, query))
print("-----COUNT-----")
query = 9
print("count: ", query, " :" , count_elem(array, query))