【问题标题】:Running a function with split loop in python在python中运行带有拆分循环的函数
【发布时间】:2021-09-03 04:49:41
【问题描述】:

我认为我没有为问题提供合适的标题。

我有一个很长的整数句子,它们之间有空格。所以,显然我正在使用.split() 方法来创建一个数组,但是这里的时间复杂度有点问题。实际上,我也在循环我刚刚创建的这个数组来解决我的问题。

我想要做的是,不要有两次循环 - 一次在 .split() 中,另一次用于解决问题。 我只是想知道如何不仅可以拆分句子,还可以在我的算法中使用 just 附加元素。

以此为例:

prices = input().split()
days = int(input())

for day in range(days):
    i = int(input())
    count = 0
    for j in prices:
        if (i>=int(j)):
            count+=1
    print(count) 

在此,我首先拆分输入,然后再循环遍历数组。我想只用一个循环来做这两个以节省时间。

提前致谢。

【问题讨论】:

  • 你不能试着把两个for循环合二为一吗?
  • 您在循环中要求用户输入,这意味着外观只能以用户输入的速度运行。内部循环会循环原始用户输入,但实际上,它可以持续多长时间。这似乎是过早的优化。您真的遇到性能问题吗?
  • 我什至不会称之为“过早的优化”——没有办法优化用户输入。要找到优化的对象 - 第一个 input() 内部循环必须替换为长度等于 days 的序列
  • 不要关注输入天数,而是输入价格。价格看起来像这样:2 3 5 10 199 354 133 13 ........所以,这只是一次输入,然后我将该输入分解为一个数组,然后我稍后循环遍历该数组,如您所见。

标签: python loops split time-complexity


【解决方案1】:

如前所述,在循环中要求用户输入是有害的。但如果这只是一个玩具示例,您可以通过以下方式改进您的算法:不将O(n) 线性运行到每个循环的prices 大小,而只是O(log n)。

import bisect

prices = [10, 20, 15, 30, 35, 25, 30, 30]
days = 7
per_day = [8, 19, 35, 22, 13, 25, 30]

# Sort the prices so we can easily know how many are the greater items for a number
prices_sorted = sorted(prices)

for day in range(days):
    i = per_day[day]
    count = bisect.bisect(prices_sorted, i)  # Now, instead of traversing the prices linearly to count how many items are lesser than i, we just have to perform a binary search on where i would be placed in the sorted sequence.
    items = prices_sorted[:count]
    print(f"{i=} {count=} {items=}")

输出

i=8 count=0 items=[]
i=19 count=2 items=[10, 15]
i=35 count=8 items=[10, 15, 20, 25, 30, 30, 30, 35]
i=22 count=3 items=[10, 15, 20]
i=13 count=1 items=[10]
i=25 count=4 items=[10, 15, 20, 25]
i=30 count=7 items=[10, 15, 20, 25, 30, 30, 30]

【讨论】:

  • 我想我不能清楚地澄清这个问题。首先,您已经有一个价格数组,然后您尝试对其进行排序。即使你的算法更快,我的问题是在使用 split() 然后循环它们时不要有 O(2n) 的时间复杂度。可能我为这个问题给出了错误的例子。不过还是谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-24
  • 2019-07-18
  • 1970-01-01
相关资源
最近更新 更多