본문 바로가기

Programming/Python46

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.
index(), find() - 원소의 인덱스 index(), find() 메소드는 원소의 인덱스 위치를 반환한다 index()는 해당 원소가 없으면 ValueError를 리턴하고, find()는 -1을 리턴한다 find()는 문자열에서만 지원한다 # tuple >>> (1,2,3,4).index(2) 1 >>> (1,2,3,4).index(5) Traceback (most recent call last): File "", line 1, in ValueError: tuple.index(x): x not in tuple >>> (1,2,3,4).find(2) Traceback (most recent call last): File "", line 1, in AttributeError: 'tuple' object has no attribute 'find'.. 2020. 9. 1.
string unpacking - 문자열 언팩킹 언팩킹이란? 요소를 여러 변수에 나누어 담는 것 locals()? 현재 scope 에 있는 local 변수를 딕셔너리 type( {key:value} ) 으로 반환 >>> nums = [1,2,3,4] # unpacking >>> a,*b = nums >>> a 1 >>> b [2,3,4] >>> f'{a} {b} {nums}' 1 [2,3,4] [1,2,3,4] # unpacking >>> '{a} {b} {nums}'.format(**locals()) 1 [2,3,4] [1,2,3,4] 2020. 8. 23.
copy - shallow, deep : 깊은복사, 얕은복사 list >>> num_list = [1,2,3,4] # deep copy >>> new_list = num_list[:] >>> new_list2 = list(num_list) set >>> str_set = {'Jane', 'Tim', 'John'} # deep copy >>> new_set = str_set.copy() dict >>> str_dict = {'hi': 'world'} # deep copy >>> new_dict = str_dict.copy() use copy module >>> import copy >>> object = 'other something object' >>> new_obj = copy.copy(object) # shallow copy >>> new_obj2 = copy.. 2020. 8. 19.