Recursion

์žฌ๊ท€ํ•จ์ˆ˜๋Š” base case์™€ recursive case๋กœ ๋‚˜๋ˆ ์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. recursive case๋Š” ๊ฐ™์€ ํ˜•ํƒœ์˜ ๋” ์ž‘์€ ๋ถ€๋ถ„ ๋ฌธ์ œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ํ‘ธ๋Š” case์ด๊ณ  base case๋Š” ๋” ์ž‘์€ ๋ถ€๋ถ„ ๋ฌธ์ œ๋กœ ๋‚˜๋ˆ„์ง€ ์•Š๊ณ ๋„ ๋ฐ”๋กœ ๋‹ต์„ ์•Œ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์ด๋‹ค. ์žฌ๊ท€ํ•จ์ˆ˜์™€ ๋ฐ˜๋ณต๋ฌธ์€ ์„œ๋กœ ์ „ํ™˜์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด

print("# n๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋ฅผ ๋ฆฌํ„ด")
# 0 1 1 2 3 5 8 13 21 ...
def fib(n):   
    if n ==1 or n == 2: # base case
        return 1
    else: # recursive case
        return fib(n-1) + fib(n-2)

# ํ…Œ์ŠคํŠธ: fib(1)๋ถ€ํ„ฐ fib(10)๊นŒ์ง€ ์ถœ๋ ฅ
for i in range(1, 11):
    print(fib(i))

ํ•ฉ

print("# 1~10๊นŒ์ง€ ํ•ฉ๊ตฌํ•˜๊ธฐ")
def triangle_number(n):
    if n == 1: # base case
        return 1    
    return n + triangle_number(n - 1) # recursive case

for i in range(1, 11):
    print(triangle_number(i))
print("# n์˜ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ์„ ๋ฆฌํ„ด")
# n = 123 โ†’ 1+2+3=6
def sum_digits(n):
    if n < 10: # base case
        return n
    else: # recursive case   
        divide = n // 10
        remain = n % 10
        return sum_digits(divide) + remain

# ํ…Œ์ŠคํŠธ
print(sum_digits(22541))
print(sum_digits(92130))
print(sum_digits(12634))
print(sum_digits(704))
print(sum_digits(3755))
print("# 1๋ถ€ํ„ฐ n ๊นŒ์ง€ ์—ฐ์†ํ•œ ์ˆซ์ž์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜")
def sum_number(n):
    return n*(n+1) // 2
   
print(sum_number(10))
print("# 1๋ถ€ํ„ฐ n ๊นŒ์ง€ ์—ฐ์†ํ•œ ์ˆซ์ž ์ œ๊ณฑ์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜")
def _sum_number(n) :
    return n*(n+1)*(2*n+1) // 6
    
print(_sum_number(3))

๋ฆฌ์ŠคํŠธ ๋’ค์ง‘๊ธฐ

print("# ํŒŒ๋ผ๋ฏธํ„ฐ some_list๋ฅผ ๊ฑฐ๊พธ๋กœ ๋’ค์ง‘๋Š” ํ•จ์ˆ˜")
def flip(some_list):
    if len(some_list) < 2:
        return some_list
    return flip(some_list[1:]) + some_list[:1]

# ํ…Œ์ŠคํŠธ
some_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
some_list = flip(some_list)
print(some_list)

Last updated