简体   繁体   中英

Function comparison

I was doing this leetcode question: https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/

My code was:

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

but this timed out, a solution was:

 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

given the for loop and the while loop. it seems like these two functions do exactly the same thing. Why does my code time out but the while loop doesn't?

The working version breaks out of the inner loop once the result of the custom function is reaches z .

You can get the same result using a break in the for loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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