简体   繁体   English

使用 python 中的列表理解在连续行上输入

[英]Taking inputs on consecutive lines using list comprehension in python

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示例:行 1:7 8 6 546 878 98 34 543
line 2: 4 6 7 8 786 2号线:4 6 7 8 786

outut: 0 1 2 -1输出: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.第二行的第一个值是要搜索的值的数字,这里是“4”,之后是上面数组中要搜索的值。

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. my_bin中的 while 循环不会终止,因为只有if and elif如果它不匹配任何条件,它将处于非终止循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM