[python] Code-kata week3-1

EMMAยท2022๋…„ 3์›” 28์ผ
0

[wecode] Code-kata

๋ชฉ๋ก ๋ณด๊ธฐ
11/12

๐Ÿ–ฅ Code-kata week3-1 ๋ฌธ์ œ


๋ฌธ์ œ
๋‘ ๊ฐœ์˜ input์—๋Š” ๋ณต์†Œ์ˆ˜(complex number)๊ฐ€ string ์œผ๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋ณต์†Œ์ˆ˜๋ž€ a+bi ์˜ ํ˜•ํƒœ๋กœ, ์‹ค์ˆ˜์™€ ํ—ˆ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์ž…๋‹ˆ๋‹ค.

input์œผ๋กœ ๋ฐ›์€ ๋‘ ์ˆ˜๋ฅผ ๊ณฑํ•ด์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”. ๋ฐ˜ํ™˜ํ•˜๋Š” ํ‘œํ˜„๋„ ๋ณต์†Œ์ˆ˜ ํ˜•ํƒœ์˜ string ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋ณต์†Œ์ˆ˜ ์ •์˜์— ์˜ํ•˜๋ฉด (i^2)๋Š” -1 ์ด๋ฏ€๋กœ (i^2) ์ผ๋•Œ๋Š” -1๋กœ ๊ณ„์‚ฐํ•ด์ฃผ์„ธ์š”.

์ œ๊ณฑ ํ‘œํ˜„์ด ์•ˆ ๋˜์–ด i์˜ 2์ œ๊ณฑ์„ (i^2)๋ผ๊ณ  ํ‘œํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

๊ฐ€์ •: input์€ ํ•ญ์ƒ a+bi ํ˜•ํƒœ์ž…๋‹ˆ๋‹ค. output๋„ a+bi ํ˜•ํƒœ๋กœ ๋‚˜์™€์•ผ ํ•ฉ๋‹ˆ๋‹ค.

Input: "1+1i", "1+1i" Output: "0+2i" ์„ค๋ช…: (1 + i) * (1 + i) = 1 + i + i + i^2 = 2i 2i๋ฅผ ๋ณต์†Œ์ˆ˜ ํ˜•ํƒœ๋กœ ๋ฐ”๊พธ๋ฉด 0+2i.

Input: "1+-1i", "1+-1i" Output: "0+-2i" ์„ค๋ช…: (1 - i) * (1 - i) = 1 - i - i + i^2 = -2i, -2i๋ฅผ ๋ณต์†Œ์ˆ˜ ํ˜•ํƒœ๋กœ ๋ฐ”๊พธ๋ฉด 0+-2i.


ํ’€์ด

์ธ์ž, ๋ฐ˜ํ™˜ํ•˜๋Š” ํ‘œํ˜„๋„ string ํ˜•ํƒœ์—ฌ์•ผ ํ•œ๋‹ค.
๊ทธ๋ž˜์„œ slicing์„ ๋ฐ”๋กœ ์ ์šฉํ•ด์„œ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

  • ๋ฐ˜ํ™˜ํ•˜๋Š” ํ˜•ํƒœ๋„ ๋ฌด์กฐ๊ฑด a+bi ํ˜•ํƒœ๋‹ค.
  • a๋Š” '+' ์ „๊นŒ์ง€ ๋ชจ๋“  ๋ฌธ์ž์—ด์— ํ•ด๋‹นํ•œ๋‹ค. (int๋กœ ๋ณ€ํ™˜)
  • b๋Š” '+' ๋‹ค์Œ๋ถ€ํ„ฐ 'i' ์ „๊นŒ์ง€์˜ ๋ฌธ์ž์—ด์— ํ•ด๋‹นํ•œ๋‹ค. (int๋กœ ๋ณ€ํ™˜)
  • i^2๋Š” -1๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค
def complex_number_multiply(a, b):
  x = int(a[:a.index('+')])
  p = int(b[:b.index('+')])
  y = int(a[a.index('+')+1:a.index('i')])
  q = int(b[b.index('+')+1:b.index('i')])
  
  result1 = (x*p - y*q)
  result2 = (x*q + y*p)
  if result1 == 0: result1 = 0
  if result2 == 0: result2 = 0
  
  # '+'๋กœ ์—ฐ๊ฒฐํ•˜๋ ค๋ฉด ๋ชจ๋‘ str ํ˜•ํƒœ์—ฌ์•ผ ํ•จ 
  return str(result1) + '+' + str(result2) + 'i'
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

0๊ฐœ์˜ ๋Œ“๊ธ€