Search code examples
python-3.xlistcomplex-numbers

Remove non-conjugates from complex numbers list


I have two lists, one contains the real part of imaginary numbers, the other contains the imaginary part of the same numbers. I want to remove from both lists the imaginary numbers that do not have a conjugate.

For example, the following lists x = [3, 4, 2, 7, 4] and y = [2, -1, 0, 6, 1] represent the numbers :

3 + 2j    <- no conjugate (to remove)
4 - 1j    <- conjugate (to keep)
2 + 0j    <- real (to keep)
4 + 1j    <- conjugate (to keep)
7 + 6j    <- no conjugate (to remove)

The expected result is the following :

new_x = [4, 2, 4]
new_y = [-1, 0, 1]

Any idea how i can achieve this ? Thanks


Solution

  • This script will find complex conjugates from lists x and y:

    x = [3, 4, 2, 7, 4]
    y = [2, -1, 0, 6, 1]
    
    tmp = {}
    for r, i in zip(x, y):
        tmp.setdefault(i, set()).add(r)
    
    x_out, y_out = [], []
    for r, i in zip(x, y):
        if i==0 or r in tmp.get(-i, []):
            x_out.append(r)
            y_out.append(i)
    
    print(x_out)
    print(y_out)
    

    Prints:

    [4, 2, 4]
    [-1, 0, 1]