在排序数组中找到大于k的数字的首次出现

时间:2019-06-12 18:45:54

标签: python-3.x

对于给定的排序列表,程序应返回列表中数字的索引,该索引大于输入的数字。

现在,当我运行代码并检查其是否正常工作时,我将获得2个输出。一个是值,其他输出是None。

如果说我在下面的代码中输入了3,则预期的输出是20的索引,即1而不是1,然后是None。

如果我给出的任何值大于列表中存在的值,我将得到正确的输出,即“输入的数字大于列表中的数字”

num_to_find = int(input("Enter the number to be found"))

a=[2,20,30]
def occur1(a,num_to_find):
    j = i = 0
    while j==0:
        if a[len(a)-1] > num_to_find:
            if num_to_find < a[i]:
                j=1
                print(i)
                break
            else:
                i = i + 1
        else:
            ret_state = "The entered number is greater than the numbers in the list"
            return ret_state

print(occur1(a,num_to_find))

2 个答案:

答案 0 :(得分:1)

由于额外的变量,变量名不佳(j通常用作索引,而不是布尔符号),break的使用,嵌套条件和{{ 3}}。它的效率也很低,因为在最坏的情况下它需要访问列表中的每个元素,并且无法充分利用列表的排序性质。但是,它似乎可以正常工作。

您的第一个误解可能是print(i)正在打印下一个最大元素的 index 而不是元素本身。在您对occur1([2, 20, 30], 3))的示例调用中,1是20驻留在数组中的位置。

第二,一旦找到的元素被打印,该函数从循环中中断后将返回None,并且print会忠实地打印None。希望这可以解释您的输出-您可以使用return a[i]代替break来解决当前的问题并满足您的期望。


话虽如此,Python为此提供了一个内置模块:side effect。这是一个示例:

from bisect import bisect_right

a = [1, 2, 5, 6, 8, 9, 15]
index_of_next_largest = bisect_right(a, 6)
print(a[index_of_next_largest]) # => 8

如果下一个大于k的数字超出范围,则可以try / except进行设置,或使用有条件的条件报告故障,并认为合适。此功能利用了使用bisect对列表进行排序的事实,该列表将搜索空间减少了一半。时间复杂度为O(log(n)),非常快。


如果您希望坚持使用类似于您的解决方案的线性算法,则可以将逻辑简化为:

def occur1(a, num_to_find):
    for n in a:
        if n > num_to_find:
            return n

# test it...
a = [2, 5, 10]

for i in range(11):
    print(i, " -> ", occur1(a, i))

输出:

0  ->  2
1  ->  2
2  ->  5
3  ->  5
4  ->  5
5  ->  10
6  ->  10
7  ->  10
8  ->  10
9  ->  10
10  ->  None

或者,如果您想要下一个最大数字的索引:

def occur1(a, num_to_find):
    for i, n in enumerate(a):
        if n > num_to_find:
            return i

但是我想强调的是,在所有方面,二进制搜索都比线性搜索要好得多。对于十亿个元素的列表,在最差的情况下,线性搜索将进行十亿个比较,二进制搜索将进行约20个比较。不使用它的唯一原因是如果不能保证列表是预先排序的,则不是这种情况。

要使其更加具体,可以使用此程序(但实际上使用内置模块):

import random

def bisect_right(a, target, lo=0, hi=None, cmps=0):
    if hi is None:
        hi = len(a)

    mid = (hi - lo) // 2 + lo
    cmps += 1

    if lo <= hi and mid < len(a):
        if a[mid] < target:
            return bisect_right(a, target, mid + 1, hi, cmps)
        elif a[mid] > target:
            return bisect_right(a, target, lo, mid - 1, cmps)
        else:
            return cmps, mid + 1

    return cmps, mid + 1

def linear_search(a, target, cmps=0):
    for i, n in enumerate(a):
        cmps += 1

        if n > target:
            return cmps, i

    return cmps, i

if __name__ == "__main__":
    random.seed(42)
    trials = 10**3
    list_size = 10**4
    binary_search_cmps = 0
    linear_search_cmps = 0

    for n in range(trials):
        test_list = sorted([random.randint(0, list_size) for _ in range(list_size)])
        test_target = random.randint(0, list_size)
        res = bisect_right(test_list, test_target)[0]
        binary_search_cmps += res
        linear_search_cmps += linear_search(test_list, test_target)[0]

    binary_search_avg = binary_search_cmps / trials
    linear_search_avg = linear_search_cmps / trials
    s = "%s search made %d comparisons across \n%d searches on random lists of %d elements\n(found the element in an average of %d comparisons\nper search)\n"
    print(s % ("binary", binary_search_cmps, trials, list_size, binary_search_avg))
    print(s % ("linear", linear_search_cmps, trials, list_size, linear_search_avg))

输出:

binary search made 12820 comparisons across
1000 searches on random lists of 10000 elements
(found the element in an average of 12 comparisons
per search)

linear search made 5013525 comparisons across
1000 searches on random lists of 10000 elements
(found the element in an average of 5013 comparisons
per search)

添加的元素越多,线性搜索的情况就越差。

答案 1 :(得分:0)

我会采取以下措施:

for (item in fileList.data) {
    for (file in fileList.data[item].files) {
         let data = fileList.data[item].files[file];

         // process the data         

    }
}

哪个给出num_to_find = int(input("Enter the number to be found")) a=[2,20,30] def occur1(a, num_to_find): for i in a: if not i <= num_to_find: return a.index(i) return "The entered number is greater than the numbers in the list" print(occur1(a, num_to_find)) 的输出(输入3时)。

您提供2条输出的原因是因为您的代码中有2条1语句。