This repository has been archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem54.py
69 lines (50 loc) · 1.8 KB
/
problem54.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#program to search a item in a list using binary search
#assume list is sorted
def binary_search(list1, item,t):
#this function returns true if item is in list1
#takes list1 and item as arguments
#t is index
print("list is:",list1)
print("item is:",item)
print("t is:",t)
#if list is empty return false
#if list has only one element ,check if it is equal to item
#if list has more than one element, check if middle element is equal to item or less than item or greater than item
#case 1 list is singular
if len(list1) == 1:
if list1[0]==item:
return True,t
else:
return False,-1 #-1 means item not found
#case 2 list is empty
elif len(list1) == 0:
return False,-1
#case 3 list has more than one element
else:
#3 cases again.if middle element is equal to item or less than item or greater than item
if list1[int(len(list1)/2)]<item:
return binary_search(list1[int(len(list1)/2)::],item,t+int(len(list1)/2))
elif list1[int(len(list1)/2)]==item:
return True,t+int(len(list1)/2)
else:
return binary_search(list1[:int(len(list1)/2):],item,t)
#generate a random list
#1 import library
import random
#2 generate list
l=[random.randint(-10,10) for i in range(10)]
l.sort()
print("list is:",l)
#3 generate item, which is to be searched
item=random.randint(-10,10)
print("Item to be searched:",item)
#search
a=binary_search(l,item,0)
print(a)
#4 check if answer is correct
print("Is answer correct?",a[0]==(item in l))
#5 print index by binary search and by index function
#item must be in list
if a[0]==True:
print("Index by binary search:",a[1])
print("Index by index function:",l.index(item))