🐍파이썬 심화(λ°μ½”λ ˆμ΄ν„°)

νŒ”λ¦¬λ™Β·2021λ…„ 5μ›” 11일

🐍파이썬 심화(λ°μ½”λ ˆμ΄ν„°)

λ°μ½”λ ˆμ΄ν„° νŠΉμ§•

  1. μž₯점
    • μ½”λ“œ μ€‘λ³΅μ œκ±° κ°€λŠ₯, μ½”λ“œκ°„κ²°
    • ν΄λ‘œμ € 보닀 문법이 κ°„κ²°
    • μ‘°ν•©ν•΄μ„œ μ‚¬μš©μ΄ μš©μ΄ν•¨
  2. 단점
    • 디버깅이 어렀움
    • μ—λŸ¬μ˜ λͺ¨ν˜Έν•¨

λ°μ½”λ ˆμ΄ν„° 예제

  • ν΄λ‘œμ € ν•¨μˆ˜λ₯Ό λ§Œλ“€μ–΄ μ£Όμ—ˆλ‹€.
  • λŒ€μΆ© ν•¨μˆ˜μ˜ μ‹€ν–‰μ‹œκ°„κ³Ό ν•¨μˆ˜λͺ…, λ§€κ°œλ³€μˆ˜,λ₯Ό 좜λ ₯ν•˜λŠ” ν˜•νƒœλ‹€.
import time

def perf_clock(func):

    def perf_clocked(*args):
        # μ‹œμž‘μ‹œκ°„ 
        st = time.perf_counter()
        result = func(*args)
        # μ’…λ£Œμ‹œκ°„ 
        et = time.perf_counter() - st 
        # ν•¨μˆ˜λͺ… 
        name = func.__name__
        # λ§€κ°œλ³€μˆ˜ 
        arg_str = ','.join(repr(arg) for arg in args)
        # 좜λ ₯ 
        print('[%0.5fs] %s(%s) -> %r' % (et, name, arg_str, result))
        return result
    return perf_clocked
  • 각각 λ‹€λ₯Έ κΈ°λŠ₯을 ν•˜λŠ” ν•¨μˆ˜3개λ₯Ό λ§Œλ“€μ—ˆλ‹€.
def time_func(seconds):
    time.sleep(seconds)


def sum_func(*numbers):
    return sum(numbers)


def fact_func(n):
    return 1 if n < 2 else n * fact_func(n-1)

λ°μ½”λ ˆμ΄ν„° λ―Έμ‚¬μš© 예제

non_deco1 = perf_clock(time_func)
non_deco2 = perf_clock(sum_func)
non_deco3 = perf_clock(fact_func)


non_deco1(2)
# [2.00034s] time_func(2) -> None
non_deco2(100, 200, 300, 400, 500) 
# [0.00000s] sum_func(100,200,300,400,500) -> 1500
non_deco3(10)
# [0.00001s] fact_func(10) -> 3628800
  • λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” 경우λ₯Ό 보면..
    • perf_clock()ν•¨μˆ˜μ˜ μΈμžμ— μ‹€ν–‰ν•˜κ³ μž ν•˜λŠ” ν•¨μˆ˜λ₯Ό λ‹΄λŠ”λ‹€.
    • 그리고 κ·Έκ±Έ λ³€μˆ˜μ— λ‹΄λŠ”λ‹€.
    • λ³€μˆ˜μ— 인자λ₯Ό λ„£μ–΄μ„œ μ‹€ν–‰ν•œλ‹€.

λ°μ½”λ ˆμ΄ν„° μ‚¬μš©μ˜ˆμ œ

@perf_clock
def time_func(seconds):
    time.sleep(seconds)

@perf_clock
def sum_func(*numbers):
    return sum(numbers)

@perf_clock
def fact_func(n):
    return 1 if n < 2 else n * fact_func(n-1)
  • ν΄λ‘œμ € ν•¨μˆ˜λ₯Ό λ§Œλ“ κ²ƒμ„ μ‹€ν–‰ν•  ν•¨μˆ˜μœ„μ— μ˜¬λ¦°λ‹€.
time_func(2)
# [2.00027s] time_func(2) -> None
sum_func(10,20,30,40,50)
# [0.00000s] sum_func(10,20,30,40,50) -> 150
fact_func(10)
# [0.00000s] fact_func(1) -> 1
# [0.00001s] fact_func(2) -> 2
# [0.00002s] fact_func(3) -> 6
# [0.00005s] fact_func(4) -> 24
# [0.00005s] fact_func(5) -> 120
# [0.00006s] fact_func(6) -> 720
# [0.00007s] fact_func(7) -> 5040
# [0.00008s] fact_func(8) -> 40320
# [0.00009s] fact_func(9) -> 362880
# [0.00010s] fact_func(10) -> 3628800
  • λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜λŠ” 경우λ₯Ό 보면...
    • μ‹€ν–‰ν•¨μˆ˜μ— 인자λ₯Ό λ„£μ–΄μ„œ μ‹€ν–‰ν•˜λ©΄ 끝!

λ°μ½”λ ˆμ΄ν„° μ„€λͺ…

λ°μ½”λ ˆμ΄ν„°λŠ” ν•¨μˆ˜λ₯Ό κ°μ‹ΈλŠ” ν˜•νƒœλ‘œ κ΅¬μ„±λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€. λ”°λΌμ„œ λ°μ½”λ ˆμ΄ν„°λŠ” κΈ°μ‘΄ ν•¨μˆ˜λ₯Ό μˆ˜μ •ν•˜μ§€ μ•ŠμœΌλ©΄μ„œ μΆ”κ°€ κΈ°λŠ₯을 κ΅¬ν˜„ν•  λ•Œ μ‚¬μš©ν•©λ‹ˆλ‹€.
좜처: https://dojang.io/mod/page/view.php?id=2427

profile
λ°°μ›€μ˜ 기둝

0개의 λŒ“κΈ€