Program/[Kaggle] 30 Days of ML

[30 Days of ML] Day 3

uding9 2021. 8. 5. 22:33
반응형

Getting Help

help() 를 사용하면 함수에 대한 설명과 어떤 인자를 받는지 알 수 있음


Defining functions

함수는 def 로 시작하고 return 문을 만나면 함수를 즉시 종료하고 오른쪽에 있는 값을 calling context에 전달함


다음은 사용자 정의 함수 생성

def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(c - a)
    return min(diff1, diff2, diff3)
help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)

함수의 설명을 추가하려면 docstring이라 불리는 설명을 추가해야 함


Docstrings

docstring은 삼중 따옴표로 묶인 문자열임

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.

    >>> least_difference(1, 5, -5)
    4"""
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(c - a)
    return min(diff1, diff2, diff3)
help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)
    Return the smallest difference between any two numbers
    among a, b and c.

    >>> least_difference(1, 5, -5)
    4

여기서 >>> 는 Python 대화형 셸에서 사용된 명령 프롬프트에 대한 참조임


Functions that don't return

Python에서 return 문이 없는 즉 None 값을 반환하는 함수 또한 정의할 수 있음

Without a return statement, least_difference is completely pointless, but a function with side effects may do something useful without returning anything. We've already seen two examples of this: print() and help() don't return anything. We only call them for their side effects (putting some text on the screen). Other examples of useful side effects include writing to a file, or modifying an input.

kaggle에서 return 문이 없는 함수의 side effect(다른 효과?)를 말하는데 화면에 텍스트 띄우기, 파일에 쓰기, 입력 수정 등으로 사용할 수 있다는 말인 듯 하다.


Default arguments

우리가 정의한 함수에 default 값이 있는 선택적 인자를 추가하는 예

def greet(who='Colin'):
    print("Hello,", who)

greet()
greet(who="Kaggle")
greet("world")
Hello, Colin
Hello, Kaggle
Hello, world

Functions Applied to Functions

함수를 다른 함수에게 인자로 제공할 수 있음

def mult_by_five(x):
    return 5*x

def call(fn, arg):
    """Call fn on arg"""
    return fn(arg)

def squared_call(fn, arg):
    """Call fn on the result of calling fn on arg"""
    return fn(fn(arg))

print(
    call(mult_by_five, 1),
    squared_call(mult_by_five, 1),
    sep = '\n'
)
5
25

다른 함수에서 작동하는 함수를 "고차 함수(higher-order function)"라고 함

파이썬에는 호출하기에 유용한 고차 함수가 내장되어 있음

선택적 key 인자를 사용해 함수를 전달하면 key(x) 를 최대화 하는 인수 x 를 반환함(일명 argmax)

def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5

print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n'
)
Which number is biggest?
100
Which number is the biggest modulo 5?
14

Exercise

2

roundndigits 가 음수일 경우 큰 숫자를 처리할 때 유용함

핀란드의 면적: 338,424km²
그린란드의 면적: 2,166,086km²

ndigits=-3 으로 round() 를 호출하여 숫자를 간단하게 나타낼 수 있음

핀란드의 면적: 338,000km²
그린란드의 면적: 2,166,000km²

반응형