In a list of tuples(where the first one is string and second one is integer) I had to find all tuples which first element starts with input string , using binary search. Before all that , I lexicographic sorted that list of tuples via first element of tuple , and after that, using binary search, adding tuples, which first element is equal to input string, to the new list. Here's my code
def binary_search(x,list):
l=0
r=len(list)-1
while l<=r:
m=(r-1)/2+l
m=int(m)
if list[m][0][0:len(x)]==x:
return list[m]
elif list[m][0][0:len(x)]<x:
l=m+1
elif list[m][0][0:len(x)]>x:
r=m-1
return -1
And then I add list of tuples that I want to new list
new_list=[]
s=input()
lexicographic_sort(list) #function that sorts using lambda
a=binary_search(s,list)
while a!=-1:
new_list.append(a)
list.remove(a)
a=binary_search(s,list)
print(new_list)
The problem is when I input just 1 character, I got results that I want, but inputting more than 1 character, the program just freeze. The more confusing problem in putting more than 1 character is that, when i remove while loop just to call one binary search, it returns me a tuple, so I don't know why my program freezes.
The list is [('school', 312), ('bus', 421), ('scheme', 53), ('and', 423), ('maybe', 143), ('schemes', 53), ('ands', 423), ('maybes', 143), ('schemess', 53), ('andsss', 423), ('maybesss', 143)]
Input 1:sc
Output:[('schemess', 53), ('school', 312), ('scheme', 53), ('schemes', 53)]
Input 2:may
Output:(freeze)
In binary search, A major step is looking at the middle element, as described in https://en.wikipedia.org/wiki/Binary_search_algorithm (among other places)
m = (r+l) // 2
You have
m=(r-1)/2+l
For example, the middle of 9 and 11 would be 10/2+9 = 14. That is not right. This can lead you to look at indexes that are too big for the array, and thus exit the program with IndexError.
You'll want to use // to guarantee an integer result. In this case, rounding down is desired.
It really should have been clear that you are getting an IndexError exception, though. No idea what's up with it supposedly freezing. That part makes no sense.