简体   繁体   中英

How can I better the perfomance of my "Is this a straight line?" algo?

I've recently started using LeetCode to straighten my algorithm performance skills and most of the time my algorithm is <80% better in Runtime and Memory Usage than of other users.

What can I do to improve the following code which is only 5% better in both Runtime and Memory Usage? What led you to an efficient solution? LeetCode problem: https://leetcode.com/problems/check-if-it-is-a-straight-line/

def checkStraightLine(self, coordinates):
    """
    :type coordinates: List[List[int]] exm1: [[1,2],[2,3],[3,4],[4,5] exm2: [[0,0],[0,5],[5,5],[5,0]]
    :rtype: bool
    """
    import numpy as np
    slope = []
    for i in range(len(coordinates)-1):
        x = coordinates[i+1][0]
        X = coordinates[i][0]
        y = coordinates[i+1][1] 
        Y = coordinates[i][1] 

        if x - X !=0:
            slope.append((y - Y) / (x - X))  #for non-zero devision cases cal. the slope

        else:
            slope.append(x) # for zero devision cases check if parlell to y axis
            print(slope)
        
    return len(np.unique(slope)) == 1 #whether slope is 0 or >0 it should be constant when comparing all given points

some considerations:

  • is not necessary to continue the loop when the first slope differ
  • is not necessary numpy for computing the unique:
import functools
from itertools import tee
def check_slope(coords):
    slope = None
    
    def pairwise(iterable):
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)

    for [x,y],[X,Y] in pairwise(coords):
        if x != X:
            v = (y - Y) / (x - X)
        else:
            v = x
        
        if slope is None:
            slope=v
        else:
            if v!=slope:
                return False
    
    return True
        
case1 = [[1,2],[2,3],[3,4],[4,5]]
case2 = [[0,0],[0,5],[5,5],[5,0]]

%timeit a = checkStraightLine(case1)
#6.78 µs ± 119 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit b = checkStraightLine(case2)
# 6.67 µs ± 47.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit c = check_slope(case1)
# 845 ns ± 50.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit d = check_slope(case2)
# 774 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

assert a==c
assert b==d






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