I want to take two lines consecutively as inputs, where the first line is my array and second array are the elements I want to search using binary search. However, after entering both lines it expects more lines and doesn't work as expected.
def my_bin(a, key):
l = 0
h = len(a) - 1
loc = -1
while(l < h):
m = l + (h - l) // 2
if (a[m] == key):
loc = m
elif (key < a[m]):
h = m
elif(key > a[m]):
l = m + 1
return loc
if __name__ == '__main__':
a = [int(x) for x in input().split()]
ktf = [int(x) for x in input().split()]
ktf = ktf[1:]
a = sorted(a)
for ele in ktf:
t = my_bin(a, ele)
print(t, end=" ")
example: line 1:7 8 6 546 878 98 34 543
line 2: 4 6 7 8 786
outut: 0 1 2 -1
First line is array to be sorted and searched. Second line has first value as number on values to search which is "4" here and after that the values to be searched in above array.
The problem is not with the input. The while loop inside your my_bin
is not terminating as you have only if and elif
if it doesn't match any of the condition it will be in a non terminating loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.