[Python] How to select element from two complex number lists to get minimum magnitude for...

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

  1. Stack

    Stack Membro Participativo

    I have two python lists(list1 and list2),each containing 51 complex numbers. At each index i, I can choose either list1 or list2. I want to select one element per index(Total of 51 elements) such that magnitude of sum of the selected complex number list is minimized.

    Sample code I have tried below:

    import random
    import itertools
    import math


    list1 = [complex(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(51)]
    list2 = [complex(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(51)]

    min_magnitude = math.inf
    for choice in itertools.product([0, 1], repeat=51):
    current = [list1 if bit == 0 else list2 for i, bit in enumerate(choice)]
    total = sum(current)
    mag = abs(total)
    if mag < min_magnitude:
    min_magnitude = mag
    best_combination = current

    print(min_magnitude)
    print(best_combination)


    it takes long time to run is there any alternative or technique to get the exact answer?

    Continue reading...

Compartilhe esta Página