[Python] Why GCD is needed in this algorithm finding all groups of three points are collinear...

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I was trying to solve this coding challenge: "Given an array of pairs, each pair (x, y), which are both integer, denotes coordinate of a point in Cartesian coordinate plane, find many groups of three points are collinear."

    It turns out this below is the correct algorithm:

    def gcd(x, y):
    if y == 0:
    return x
    else:
    return gcd(y, x % y)

    def how_many_3point_in_line( points ):
    ans = 0
    n = len( points )
    for i in range( n - 2 ):
    slopes = defaultdict( int )
    for j in range( i + 1, n ):
    dy, dx = points[1] - points[j][1], points[0] - points[j][0]
    gcd_num = gcd( dx, dy )
    slopes[( dy // gcd_num, dx // gcd_num )] += 1
    for _, occ in slopes.items():
    ans += math.comb( occ, 2 )
    return ans


    Apparently the gcd is used to represent slope, what issue does it address?

    Continue reading...

Compartilhe esta Página