[๐Ÿค”Code Kata] 3week-4,5

6490 ๋‹จ์–ด pythoncodekataWeCodeWeCode

-DAY4-

<๋ฌธ์ œ>
์ฃผ์–ด์ง„ ์ˆซ์ž ๋ฐฐ์—ด์—์„œ, 0์„ ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰์ชฝ์œผ๋กœ ์ด๋™์‹œ์ผœ์ฃผ์„ธ์š”.
์›๋ž˜ ์žˆ๋˜ ์ˆซ์ž์˜ ์ˆœ์„œ๋Š” ๋ฐ”๊พธ์ง€ ๋ง์•„์ฃผ์„ธ์š”.
์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ด์„œ๋Š” ์•ˆ ๋ฉ๋‹ˆ๋‹ค.
Input: [0,1,0,3,12] -> Output: [1,3,12,0,0]

์ ‘๊ทผ๋ฐฉ๋ฒ•

์ƒ๊ฐ๋ณด๋‹ค์‰ฌ์šด๋ฐ?๋Š” ์•„๋‹ˆ๊ณ ,
๋จผ์ € 0์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ๊ณ , ๊ทธ๋‹ค์Œ ๋ฆฌ์ŠคํŠธ์•ˆ์— ์š”์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋งค์„œ๋“œ๋ฅผ ์ด์šฉํ•ด์„œ 0์„ ์ œ๊ฑฐํ•œ๋’ค ๋งˆ์ง€๋ง‰์œผ๋กœ append๋ฅผ ํ†ตํ•ด ๋งˆ์ง€๋ง‰๋ถ€๋ถ„์— ์ฒ˜์Œ์— ์„ธ์–ด๋‘” 0์˜ ๊ฐฏ์ˆ˜๋งŒํผ 0์„ ์ถ”๊ฐ€ํ•˜๋Š”๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ–ˆ๋‹ค.

def move_zeroes(nums):
  # ์—ฌ๊ธฐ์— ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”
  test = nums.count(0)
  while test != 0:
    nums.remove(0)
    nums.append(0)
    test -= 1
  return nums

Model Solutions

def moveZeroes(nums):
  last0 = 0
  
  for i in range(0, len(nums)):
    if nums[i] != 0:
      nums[i], nums[last0] = nums[last0], nums[i]
      last0 += 1
      
  return nums

0์„ ์‚ฌ์ „์— ์ง€์ •ํ•œ๋’ค ์ˆซ์ž๋ฅผ ๋ฐ”๊พธ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์ง„ํ–‰ํ–ˆ๋‹ค.
์‹ ๋ฐ•ํ•œ๋ฐฉ๋ฒ•!!! ๋‚ด๊ฐ€ ์ œ์ผ ์–ด๋ ค์›Œํ•˜๋Š” ๊ฐœ๋…์ด nums[i], nums[last0] = nums[last0], nums[i]์ธ๋ฐ ์ง„์งœ ๋งค๋ฒˆ ๋ณผ์ˆ˜๋ก ์‹ ๊ธฐํ•˜๋‹ค ใ…Žใ…Ž..

-DAY5-

<๋ฌธ์ œ>
์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒฉํ† ๋ฆฌ์–ผ(factorial)์„ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ์„ธ์š”.
ํŒฉํ† ๋ฆฌ์–ผ์ด๋ž€ 1์—์„œ๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ •์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ณฑํ•œ๊ฒƒ์„ ๋งํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ
1! = 1
2! = 1 2
5! = 1 2 3 4 * 5

์ ‘๊ทผ๋ฐฉ๋ฒ•

์žฌ๊ท€ ํ•จ์ˆ˜(recursion)์— ๋Œ€ํ•œ ๋‚ด์šฉ์ด์˜€๋‹ค.
๋ฌธ์ œ์ž์ฒด๋Š” ์‰ฌ์šด๋ฐ, ์ƒˆ๋กœ์šด ๊ฐœ๋…์ด๋ผ ํ•œ๋ฒˆ ๊ตฌ๊ธ€๋ง์œผ๋กœ ๊ฐœ๋…์„ ์ •๋ฆฌํ•˜๊ณ  ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

def factorial(n):
  if n == 0:
    return 1
  return n * factorial(n-1)

์žฌ๊ท€ ํ•จ์ˆ˜(recursion)

ํ•จ์ˆ˜์•ˆ์—์„œ ํ•จ์ˆ˜๋ณธ์ธ์„ ์‹คํ–‰ํ•˜์—ฌ ๋ฐ˜๋ณตํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๋ญ”์†Œ๋ฆฐ๊ฐ€ ์‹ถ๊ฒ ์ง€๋งŒ, ์ž์„ธํžˆ ๋ณด๋ฉด ์ด๋Ÿฌํ•˜๋‹ค.

def recursion_print():
      print("ํ•จ์ˆ˜ ์‹คํ–‰")
      recursion_print()

recursion_print()

๊ฒฐ๊ณผ๊ฐ’์€

ํ•จ์ˆ˜ ์‹คํ–‰
ํ•จ์ˆ˜ ์‹คํ–‰
...
ํ•จ์ˆ˜ ์‹คํ–‰
RecursionError: maximum recursion depth exceeded while calling a Python object

๋กœ ๋˜๋Š”๋ฐ ์žฌ๊ท€ํ•จ์ˆ˜๋Š” ๋ฌดํ•œํ• ๊ฑฐ ๊ฐ™์ง€๋งŒ ๋ฐ˜๋ณตํ•  ์ˆ˜ ์žˆ๋Š” ํšŸ์ˆ˜๊ฐ€ ํ•œ์ •๋˜์–ด์žˆ๋‹ค(์‚ฌ๋žŒ์ด ๋ณด๊ธฐ์—” ๋ฌดํ•œํ•˜์ง€๋งŒ..) ๋˜ํ•œ ์žฌ๊ท€ ํ•จ์ˆ˜๋Š” ์กฐ๊ฑด๋ฌธ์„ ํ†ตํ•ด์„œ ์ œ์–ด๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

Model Solution

def factorial(n):
  if (n == 0):
    return 1
    
  return n * factorial(n-1)

๋‚ด๊ฐ€ ์ ‘๊ทผํ•œ ๋ฐฉ๋ฒ•๊ณผ ๋™์ผํ•˜๋‹ค~ ์–ํ˜ธโญ๏ธ

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ