Language/Python

[Python ]Practice algorithm - multiplication of complex number

청렴결백한 만능 재주꾼 2020. 7. 28. 17:59
반응형

Multiplication of complex number

Given two complex numbers. The task is to multiply them.

 

My answer: 

 

def complexNumberMultiply(a, b):
    sa = a.split('+')
    a1 = sa[0]
    a2 = sa[1]
    sb = b.split('+')
    b1 = sb[0]
    b2 = sb[1]
    ab1 = str(int((float(a1)*float(b1)) + (float(a2.strip('i'))*float(b2.strip('i')) * -1)))
    ab2 = str(int((float(a1)*float(b2.strip('i'))+(float(a2.strip('i'))*float(b1)))))+'i'
           
    return ab1 +'+'+ ab2

 

 

Model solutions:

 

def complexNumberMultiply(a, b):
  """
  :type a: str
  :type b: str
  :rtype: str
  """

  firstArr = a[:-1].split('+')
  a1 = int(firstArr[0])
  a2 = int(firstArr[1])

  secondArr = b[:-1].split('+')
  b1 = int(secondArr[0])
  b2 = int(secondArr[1])
  
  return f'{a1 * b1 - a2 * b2}+{a1 * b2 + a2 * b1}i'

# 2
def complexNumberMultiply2(a, b):
  """
  :type a: str
  :type b: str
  :rtype: str
  """
  a1, a2 = map(int, a[:-1].split('+'))
  b1, b2 = map(int, b[:-1].split('+'))
  return '%d+%di' % (a1 * b1 - a2 * b2, a1 * b2 + a2 * b1)
반응형