是否有任何提示可以让我的 Python 代码更快地用于 Hackerrank?
Are there any tips to make my Python code faster for Hackerrank?
我正在尝试解决 Hackerrank 的编码问题,但由于我的代码耗时太长 运行,连续 运行 出现超时错误。我知道它工作得很好,缩进不是问题,代码根本没有 'wrong' 。我只需要有关如何更有效地 运行 的提示:
def main(n, o, q, m):
for x in m:
for y,z in enumerate(o):
x -= z
if x<=0:
print y+1
break
if x>0: print -1
o and m are a list of integers that are looped through subtracting the values of o from m until m is less than 0, the loop finishes and m is still not less than 0 it will print -1. The ultimate goal is to find which int from o finishes m.
您正在使用 o
对 m
的每个循环执行减法。
要提高性能,您需要减少循环 m
或减少循环 o
。
减少o
循环的一种方法是预先计算所有部分和。
x
从 o
中减去值。也许您只会减去一个、两个或一千个数字。谁知道?您将为 m
.
的每个循环执行此操作
例如,如果 x
为 10,而 o
为 [2, 4, 6, 8]
,则第三项将完成循环,第三项为 12
, 2
、4
和 6
.
的总和
构建部分和列表意味着加法只需要进行一次。
itertools.accumulate
可以为您做到这一点。
如果 o
值可以是正数或负数,那么您需要进行线性搜索,因为部分总和不会按升序排列。 (也许你可以使用一个聪明的数据结构,但我不知道。)
但是,如果 o
值都是正数,您可以对部分和进行二进制搜索。
见this answer to Python binary search-like function to find first number in sorted list greater than a specific value
我正在尝试解决 Hackerrank 的编码问题,但由于我的代码耗时太长 运行,连续 运行 出现超时错误。我知道它工作得很好,缩进不是问题,代码根本没有 'wrong' 。我只需要有关如何更有效地 运行 的提示:
def main(n, o, q, m):
for x in m:
for y,z in enumerate(o):
x -= z
if x<=0:
print y+1
break
if x>0: print -1
o and m are a list of integers that are looped through subtracting the values of o from m until m is less than 0, the loop finishes and m is still not less than 0 it will print -1. The ultimate goal is to find which int from o finishes m.
您正在使用 o
对 m
的每个循环执行减法。
要提高性能,您需要减少循环 m
或减少循环 o
。
减少o
循环的一种方法是预先计算所有部分和。
x
从 o
中减去值。也许您只会减去一个、两个或一千个数字。谁知道?您将为 m
.
例如,如果 x
为 10,而 o
为 [2, 4, 6, 8]
,则第三项将完成循环,第三项为 12
, 2
、4
和 6
.
构建部分和列表意味着加法只需要进行一次。
itertools.accumulate
可以为您做到这一点。
如果 o
值可以是正数或负数,那么您需要进行线性搜索,因为部分总和不会按升序排列。 (也许你可以使用一个聪明的数据结构,但我不知道。)
但是,如果 o
值都是正数,您可以对部分和进行二进制搜索。
见this answer to Python binary search-like function to find first number in sorted list greater than a specific value