[Python] converting coordinates given in list of tuples to complex number

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have written the following code for calculating the closest pair in a plane. The code works fine but I have two questions. First, is there a shorter/better way to convert the representation of points from tuples to complex in the first function? and second, is the way I have passed the first function to the second function correct?

    import sys

    x = [1, 4]
    y = [1, 5]


    def to_complex(hor, ver):
    list_of_points = list(zip(hor, ver))
    list_of_points.sort(key=lambda el: (el[0], el[1]))
    complex_points = [complex(item[0], item[1]) for item in list_of_points]
    return complex_points


    # Brute force algorithm.


    def brute_force(points=to_complex(x, y)):
    n = len(points)
    if n < 2:
    return sys.maxsize
    else:
    min_distance = sys.maxsize
    for i in range(n):
    for j in range(i + 1, n):
    if abs(points - points[j]) < min_distance:
    min_distance = abs(points - points[j])
    closest_pair = (points, points[j])

    return min_distance, closest_pair


    print(brute_force())

    Continue reading...

Compartilhe esta Página