본문 바로가기

Python50

module - 모듈 python 에서 module 은 def를 사용하여 정의한다 def가 실행되면, 함수의 객체와 참조가 같이 생성된다 return값을 설정하지 않으면 python은 자동으로 None을 반환한다 C 언어와 같이, 아무런 값을 반환하지 않는 함수는 procedure(프로시저)라고 부른다 함수가 호출될 때마다 active record(활성화 레코드)가 생성된다 활성화 레코드에는 함수의 정보가 기록되며, 이를 stack에 저장한다함수의 정보 (반환값, 매개변수, 지역변수, 반환주소) 모듈생성 시 주의점 - 모듈의 기본값 모듈을 생성할 때, 함수 또는 매서드에서 가변객체를 기본값으로 사용하면 안된다 # 나쁜 예 def method(number, number_list=[]): number_list.append(num.. 2020. 9. 18.
setdefault() - dictionary의 키 존재 상관없이 setdefault() dict타입의 키 존재 여부를 모른 채 접근할 수 있다 A.setdefault(key, default) collections.defaultdict을 활용할 수 도 있다, 초기화시 default값을 넣어준다 A = defaultdict(list) @print_method def usual_dict(dict_data): """ dict[key]. """ newdata = {} for k, v in dict_data: if k in newdata: newdata[k].append(v) else: newdata[k] = [v] return newdata @print_method def setdefault_dict(dict_data): """ setdefault() method. """ n.. 2020. 9. 17.
Reverse list - 리스트 역순으로 list의 reverse 방법은 list.reverse(), reversed(list), list[::-1], [list.pop() for _ in list] 가 있다 더 있으면 리플달아주세요. 속도는 아래 순이다 list.reverse() < list[::-1] < reversed(list) < [list.pop() for _ in list] l=list(range(2000000)) fidx=1999999 @print_method def use_reverse(): tl = l[:] tl.reverse() print(tl[fidx]) @print_method def use_reversed(): # list를 새로 만든다 tl = l[:] tl = list(reversed(tl)) print(tl[fidx.. 2020. 9. 16.
list method 성능 측정 list 를 만들 때, +, append, comprehension 등을 사용한다 각각의 성능측정 결과, 상황에 맞게 잘 사용하면 좋을 것 같다 le = 1000000 @print_method def test_concat(): # O(k) l=[] for i in range(le): l+=[i] @print_method def test_append(): # O(1) l=[] for i in range(le): l.append(i) @print_method def test_comprehension(): l=[i for i in range(le)] @print_method def test_range(): l=list(range(le)) test_concat() test_append() test_compreh.. 2020. 9. 15.
Index(), bisect() - list 원소의 index값 찾기 list의 index값을 찾는 방법 index를 찾는 list의 크기가 크거나 loop로 찾는다면 bisect() 이진분할 알고리즘을 사용하면 시간을 단축할 수 있다 list.index(n) # list index함수 bisect(list, n) # 이진분할 알고리즘 rmax = 2000000 l = [i for i in range(rmax)] loop = 50 find_n = rmax-2 @print_time def m_index(): for i in range(loop): l.index(find_n) import bisect @print_time def m_bisect(): for i in range(loop): idx = bisect.bisect_left(l, find_n) m_index() m_b.. 2020. 9. 14.
decorator - 데커레이터 decorator 패턴은 '@'표기를 사용해 함수 또는 메서드의 변환을 우아하게 지정해준다 '함수의 객체'와 '함수를 변경하는 다른 객체'의 wrapping을 허용한다 @deco def method(arg): # method... pass decorator 를 사용한 위 코드는 아래코드와 같다 def method(arg): # method... pass method = deco(method) import functools import time def print_time_func(func): @functools.wraps(func) def wrapper(*args, **kargs): st = time.time() res = func(*args, **kargs) print(f'{func.__name__}: .. 2020. 9. 12.
named tuple - 네임드듀플 namedtuple은 tuple과 비슷한 성능과 특성을 갖는다 tuple 항목을 index 위치뿐 아니라 name으로도 참조할 수 있다 >>> from collections import namedtuple >>> >>> Animal = namedtuple('Animal', 'name species sex') >>> # Animal = namedtuple('Animal', ['name','species','sex']) ... # Animal = namedtuple('Animal', ('name','species','sex')) ... a = Animal('pororo', 'penguin', 'male') >>> a Animal(name='pororo', species='penguin', sex='male'.. 2020. 9. 11.
permutations in itertools permutations(순열) 서로다른 n개의 원소에서 서로 다른 r개의 원소를 선택하여 나열한 것 # 순열: 서로다른 n개의 원소에서 서로 다른 r개의 원소를 선택하여 나열한 것 from itertools import permutations data = 'ABC' n = len(data) r = 2 result = list(permutations(data, r)) print(result) [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')] print([''.join(dp) for dp in result]) ['AB', 'AC', 'BA', 'BC', 'CA', 'CB'] 2020. 9. 4.
list[::], tuple[::] - extended slices python에서 list, tuple를 자를 때, 효과적인 방법 list[start index:end index+1:step] >>> list_int = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # slice >>> list_int[:2] [0, 1] >>> list_int[0:2] [0, 1] >>> list_int[:5] [0, 1, 2, 3, 4] >>> list_int[2:5] [2, 3, 4] >>> list_int[::1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # even >>> list_int[::2] [0, 2, 4, 6, 8] # odd >>> list_int[1::2] [1, 3, 5, 7, 9] >>> list_int[::3] [0, 3, 6, 9] #.. 2020. 9. 2.