반응형

오늘은 Day3이다! 이번주는 파이썬 기초를 다룬다. 가볍게 Assignment를 수행하자!

Today's Assignment - day 3

tutorial 스크립트를 가볍게 읽어보고, exercise를 수행하면 된다! 
파이썬 코스 Lesson2를 수행해보자!

어떤 함수를 어떻게 사용하는지 생각이 나지 않는다면, help()함수를 이용하자.
구글링 할 필요없이, 키워드, 함수, 클래스, 메서드등에 대해 간단히 알려준다.

help(round(-2.01))

Help on int object:

class int(object)
 |  int([x]) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __ceil__(...)
 |      Ceiling of an Integral returns itself.
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floor__(...)
 |      Flooring an Integral returns itself.
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(self, format_spec, /)
 |      Default object formatter.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(self, /)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __index__(self, /)
 |      Return self converted to an integer, if self is suitable for use as an index into a list.
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __invert__(self, /)
 |      ~self
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lshift__(self, value, /)
 |      Return self<<value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rlshift__(self, value, /)
 |      Return value<<self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __round__(...)
 |      Rounding an Integral returns itself.
 |      Rounding with an ndigits argument also returns an integer.
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rrshift__(self, value, /)
 |      Return value>>self.
 |  
 |  __rshift__(self, value, /)
 |      Return self>>value.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(self, /)
 |      Returns size in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  bit_length(self, /)
 |      Number of bits necessary to represent self in binary.
 |      
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  to_bytes(self, /, length, byteorder, *, signed=False)
 |      Return an array of bytes representing an integer.
 |      
 |      length
 |        Length of bytes object to use.  An OverflowError is raised if the
 |        integer is not representable with the given number of bytes.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Determines whether two's complement is used to represent the integer.
 |        If signed is False and a negative integer is given, an OverflowError
 |        is raised.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  from_bytes(bytes, byteorder, *, signed=False) from builtins.type
 |      Return the integer represented by the given array of bytes.
 |      
 |      bytes
 |        Holds the array of bytes to convert.  The argument must either
 |        support the buffer protocol or be an iterable object producing bytes.
 |        Bytes and bytearray are examples of built-in objects that support the
 |        buffer protocol.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Indicates whether two's complement is used to represent the integer.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number

help(round(-2.01)을 실행시키면 위와같이 나온다.

이번엔 help(print)를 실행해 보겠다.

help(print)

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

print와 관련된 설명을 볼 수 있다.

Defining functions

함수를 정의하는 예시이다.

def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

위 예제를 실행하면  a, b, c 라는 세가지 인수를 사용하는 least_difference라는 함수가 생성된다.
함수는 def라는 키워드헤더로 시작한다. 들여쓰기를 신경써야 한다.
그리고 return은 함수 반환값이라고 하는데, 함수당 1개만 존재 할 수 있다. 


내가 진행하고 있는 Python Basic Grammar Review에서 함수부분 리뷰를 보면,
함수는 반환값이 존재할수도 있고, 존재하지 않는 함수도 있지만 중요한건
만약 함수의 반환값이 존재하면, 함수의 반환값은 1개가 유일하다는 것을 강조했었다.

함수는 실행중에 return을 마주치면, 즉시 함수를 종료하고 값을 반환한다.

print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)

계산했을 때, 차가 가장 작은 값들이 반환됐다.

예시를 보자. 파이썬은, 내가 작성한 함수까지 help()지원하지는 않는다.
하지만, docstring이라는 이름으로 설명을 제공할 수 있다.

Docstrings

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(a - c)
    return min(diff1, diff2, diff3)

docstring은 함수의 헤더 바로 뒤에 오는 세 개의 따옴표로 묶인 문자열(여러 줄에 걸쳐 있을 수 있음)이다.
함수에서 help()를 호출하면 docstring이 표시 된다.

자신이 정의한 함수에 대한 설명을 docstring 을 이용해서 표기해놓으면, 프로젝트를 관리하기에 용이할 것이다.

위 예제는 정의한 함수에 대한 help()를 사용한 것이다.

docstirng을 이용해서 프로젝트를 잘 관리하는 습관을 길러야 겠다.

 

Default arguments

print()를 할 때, sep를 통해 인수들 사이에 특수 문자열을 넣을 수 있다.

사용법이 매우 간단하다.  sep를 사용하지 않고, 그냥 print()를 하면 아래와 같다.

이번에는, 함수정의와 관련된 내용이다.

def greet(who="Colin"):
    print("Hello,", who)
    
greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")

위 예제를 실행시키면 어떤 문장을 볼 수 있을까?

greet()는 기본값으로 지정되어있는 Colin이 그대로 출력되었고,
greet(who="Kaggle")는 Kaggle이 출력되었고,
greet("world") 는 "world'가 자동적으로 who를 가리키는것으로 인식되어 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', # '\n' is the newline character - it starts a new line
)

위 예제를 분석해 보자. 
call(mult_by_five, 1) 은 mult_by_five라는 함수에 1을 대입한 값일 것이다. 
def call의 return값이 fn(arg)인데 이때 fn은 mult_by_five이고, arg는 1이기 때문이다.

다음 squared_call(mult_by_five, 1)을 보자.
squared_call의 return은  fn(fn(arg))이다.
이때 fn은 mult_by_five이고 arg는 1이다. 
fn(fn(arg))에서 내부에있는 fn(arg)는 앞선 call의 retrun값과 같다.
그리고 그러면 내부에있는 fn(arg)의 값은 5가된다.
fn(5)는 또다시 mult_by_five함수에 5를 대입한 값이 된다.
따라서 5 * 5 로 25가 출력될 것이다.
그리고 sep = '\n'으로 인해 각 출력물은 한줄에 하나씩 출력된다.



그다음 예제를 보도록 하자.

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',
)

mod_5함수는 x를 5로 나눈것의 나머지를 반환한다.
print문을 보면, max의 경우 가장 큰 값을 반환한다.
첫번째 max(100, 51, 14)에서는 100이 가장 크기 떄문에 100을 반환한다.
두번째 max(100, 51, 14, key=mod_5)의 경우에는 100, 51, 14를 5로 나눈 것의 나머지를 각각 비교하여 나머지가 가장 큰 값을 반환한다. 따라서 14를 반환한다.


자 이제 exercise로 가보자!

exercise를 정리한 코드를 공유한다!! 내일도 착실히 Assignment를 수행하자!!
https://github.com/mgkim-developer/30-Days-of-ML-with-Kaggle/blob/main/30-days-of-ml-day-3.ipynb

 

GitHub - mgkim-developer/30-Days-of-ML-with-Kaggle: 30 Days of ML with Kaggle

30 Days of ML with Kaggle. Contribute to mgkim-developer/30-Days-of-ML-with-Kaggle development by creating an account on GitHub.

github.com

 

반응형