1

I am writing a function that calculates complex number multiplication using python2.7. The funtion is:

def complexNumberMultiply(self, a, b):
    """
    :type a: str
    :type b: str
    :rtype: str
    """
    c,d = a.split('+')
    e,f = b.split('+')
    d = int(d[:-1])
    f = int(f[:-1])

    print c,d,e,f
    return '%s+%si' % (c * e - d * f, c * f + d * e)

But when I run it, I get this error:

In complexNumberMultiply return '%s+%si' % (c * e - d * f, c * f + d * e)
TypeError: can't multiply sequence by non-int of type 'str'

My questions is, why my int(d[:-1]) didn't turn the string (e.g. -2) into an integer?

Sara_Hsu
  • 57
  • 4
  • 4
    1) provide the input you use to test this function 2) you don't convert `c` and `e` 3) are you aware that there is a complex number type in python? –  Jun 28 '17 at 09:28

2 Answers2

2

You converted d and f to int, but what about c and e? You are trying to do c * e and you can't multiply a string by a string.

Consider:

def complexNumberMultiply(a, b):
    """
    :type a: str
    :type b: str
    :rtype: str
    """
    split_a = a.split('+')
    split_b = b.split('+')
    c, d = int(split_a[0]), int(split_a[-1][0])
    e, f = int(split_b[0]), int(split_b[-1][0])

    print (c,d,e,f)
    return '%s + %si' % (c * e - d * f, c * f + d * e)

print(complexNumberMultiply('1+2i', '3+4i'))
# 1 2 3 4
# -5+10i

Or use complex which is a builtin type in Python:

>>> complex('1+2j') * complex('3+4j')
(-5+10j)
>>> (1+2j) * (3+4j)
(-5+10j)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

Imaginary numbers are recognized in Python as objects, just like integers, floats...:

>>> complexN = 33 + 2j
>>> complexN 
(33+2j)
>>> complexN.real          # real part
33.0
>>> complexN.imag          # imaginary part
2.0

Addition of complex numbers:

>>> complex + (33+2j)
(66+4j)

the 2j is the imaginary part and the real part being 33. This is the recommended way to deal with complex numbers in Python.

But if you insist on using your function for experimenting, I don't think using str and then converting to int is a good way. Why not just use numbers straightforward? This way you'll avoid the bells and whistles of formatting the inputs to your function.

Also see: Complex numbers usage in python

GIZ
  • 4,409
  • 1
  • 24
  • 43