功能比较



我在做这个leetcode问题:https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/

我的代码是:

res = []
for x in range(1,1001):
for y in range(1000,0,-1):
test = customfunction.f(x,y)
if test == z:
res.append([x,y])
return res

但是这超时了,一个解决方案是:

def findSolution(self, customfunction, z):
res = []
y = 1000
for x in xrange(1, 1001):
while y > 1 and customfunction.f(x, y) > z:
y -= 1
if customfunction.f(x, y) == z:
res.append([x, y])
return res

给定for循环和while循环。这两个函数的作用似乎完全相同。为什么我的代码超时了,而while循环没有?

一旦自定义函数的结果达到z,工作版本就会脱离内部循环。

for循环中使用break可以获得相同的结果。

for x in range(1,1001):
for y in range(1000,0,-1):
test = customfunction.f(x,y)
if test == z:
res.append([x,y])
elif test < z:
break

最新更新