Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving real and imaginary part of complex numbers stored as strings in a list

I've done this to recover the first part of the string, for example: the "13" of "13+i":

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l2 = [i.split('+')[0] for i in l1]
l2 = list(map(int, l2))

It worked well and then I want the "1" from "13+i" but it is more complicated ever since the "i" in the string got no "1" factor.

I should get:

[1, 4, 2, 4, 1, 2, 4]

i.e., only the imaginary part of the complex number in an array.

Any idea to help me solve this?

like image 365
GabrielT Avatar asked Mar 07 '23 02:03

GabrielT


1 Answers

Python has a way of dealing with complex numbers; it actually has a type for them (<class 'complex'>). As a result, and to avoid having to re-invent the wheel I would strongly recommend using that.

To do that, we must first sanitise our input (convert the values from strings to complex). To do that we must first adhere to Python's conventions for the imaginary unit for which 'j' is used and not 'i'.

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l1 = [complex(x.replace('i', 'j')) for x in l1]

# if you are curious how they look like
print(l1)
# -> [(13+1j), (1+4j), ...]

With the values now in a proper format, we can take advantage of the .real and .imag attributes of variables of type complex and built our result lists using list-compehensions.

real_parts = [value.real for value in l1]
print(real_parts) 
# -> [13.0, 1.0, 3.0, 11.0, 5.0, 10.0, 5.0]

imaginary_parts = [value.imag for value in l1]
print(imaginary_parts)
# -> [1.0, 4.0, 2.0, 4.0, 1.0, 2.0, 4.0]

Note that by default, they are all real numbers (real as in not-integer). Casting them to int could easily be achieved with [int(value.real) for value in l1].

Probably the nicest thing about using existing functionality is that you do not have to worry about edge cases which you might have not though possible and as a result might have caused your code to break. For instance 4j (no real part) or 1-j (negative imaginary part so .split('+')[0] would not work) and so on.

like image 78
Ma0 Avatar answered Mar 09 '23 16:03

Ma0