[부스트캠프 AI tech Python Basic] week01 (2022.01.19)

Python Basics for AI(3-1)

Data structure

stack(LIFO, 후입선출)

lst = [1, 2, 3, 4, 5]
lst.append(10)
lst.append(20)
lst.pop() #20
lst.pop() #10

Queue(FIFO, 선입선출)

lst = [1, 2, 3, 4, 5]
lst.append(10)
lst.append(20)
lst.pop(0) # 1
lst.pop(0) # 2

set(집합)

s1 = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6}
s1.union(s2) # {1, 2, 3, 4, 5, 6}
s1.intersection(s2) # {3, 4, 5}
s1.difference(s2) # {1, 2}

collections.deque

  • rotate, reverse 등 Linked list의 특성을 지원
  • list보다 효율적인 자료구조를 제공, 처리속도 향상
from collections import deque
deque_list = deque([0, 1, 2, 3, 4)
deque_list.appendleft(10) # [10, 0, 1, 2, 3, 4]
deque.rotate(1) # [4, 10 ,0 ,1, 2, 3, 4]
  • %timeit: 시간을 재주는 매직커맨드

collections.defaultdict

  • 사전에 없는 값 입력시 default값 출력
from collections import defaultdict
d = defaultdict(lambda : 0)
d['ㅇㅁㅇㅁㄴㅇ'] = 0

collcetions.Counter

  • 숫자세기 / 집합연산 제공
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c + d # Counter({'a':5, 'b':4, 'c':3, 'd':2})
c & d # Counter({'b':2, 'a':1})
c | d # Counter({'a':4, 'b':2, 'c':3, 'd':4})

collections.namedtuple

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=11, y=22)
p.x + p.y # 33

그 외

from collections import OrderedDict

Python Basics for AI(3-2)

Pythonic code

  • nested loop 출력할 때 pprint로 출력하면 깔끔함
  • lambda는 자제할 것
  • maplist comprehension으로 대체 권장

reduce

from functools import reduce
reduce(lambda x, y : x + y, [1, 2, 3, 4, 5])

generator comprehension

gen_ex = (n*n for n in range(100))

variable-length asterisk

def asterisk_test(a, b, *args):
	return a+b+sum(args)   # args-> tuple
asterisk_test(1, 2, 3, 4, 5)

keyword variable-length asterisk

def kwargs_test_1(**kwargs):
	print(kwargs) # kwargs->dict
def kwargs_test(one, two=3, *args, **kwargs):
    print(one+two+sum(args))
    print(args)
    print(kwargs)
return
kwargs_test(10, 30, 3, 5, 6, 7, 8, first=3, second=4, third=5)
69
(3, 5, 6, 7, 8)
{'first': 3, 'second': 4, 'third': 5}

unpacking

def asterisk_test(a, *args):
    print(a, *args)
    print(a, args)
    print(type(args))
test = (2, 3, 4, 5, 6)
asterisk_test(1, *test)
return
1 2 3 4 5 6
1 (2, 3, 4, 5, 6)
<class 'tuple'>

unpacking with zip

ex = ([1, 2], [3, 4], [5, 6])
for value in zip(*ex):
    print(value)
return
(1, 3, 5)
(2, 4, 6)

Python Basics for AI(4-1)

OOP

def __str__(self): 클래스 print시 출력되는 문자열
def __add__(self, other): 다른 객체와 연산
self.__items: private 속성

first-class object

python에서는 함수를 파라메터/리턴 값으로 사용 가능

def square(x):
	return x * x
f = square
f(5)

inner function

  • closures: inner function을 return값으로 반환
def print_msg(msg):
	def printer():
    	print(msg)
    return printer
another = print_msg('Hello, Python')
another()

return

Hello, Python

decorator

def star(func):
    def inner(*args, **kwargs):
        print('*' * 30)
        func(*args, **kwargs)
        print('*' * 30)
    return inner
@star
def printer(msg):
    print(msg)
print("Hello")

return

******************************
Hello
******************************

def star(func):
    def inner(*args, **kwargs):
        print('*' * 30)
        func(*args, **kwargs)
        print('*' * 30)
    return inner
def percent(func):
    def inner(*args, **kwargs):
        print('%' * 30)
        func(*args, **kwargs)
        print('%' * 30)
    return inner
@star
@percent
def printer(msg):
    print(msg)
printer('Hello')

return

******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hello
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************

def generate_power(exponent):
    def wrapper(f):
        def inner(*args):
            result = f(*args)
            return exponent ** result
        return inner
    return wrapper
@generate_power(2)
def raise_two(n):
    return n**2
print(raise_two(7))

return

562949953421312

좋은 웹페이지 즐겨찾기