[Day3] 파이썬 기초 문법II

 

중요

코드 시간 측정

import time
start= time.clock()
​``` code ```
print(time.clock()-start)

보통 다음과 같은 방법을 사용하는데 time.clock()함수는 이제 사용 못하게 된다.(파이썬 3.8 버전부터 없어질 예정)

이제 perf_counterprocess_time를 사용할 수 있는데 차이점이 있다.

 

perf_counter: sleep함수를 호출하여 대기한 시간까지 포함하여 측정.

process_time: 실제로 연산하는데 걸린 시간만 측정.

import time

def process1():
    start = time.perf_counter()
    time.sleep(1)
    return (time.perf_counter()-start)

def process2():
    start = time.process_time()
    time.sleep(1)
    return (time.process_time()-start)


print('use perf_counter :', process1(), 'sec') # use perf_counter : 1.012900000000002 sec
print('use process_time :', process2(), 'sec') # use process_time : 0.0 sec

 

쥬피터에서는 시간측정은 다음과 같이 할 수 있다.

from collections import deque

def deque_list():
    deque_list =deque()
    for i in range(10000):
        for i in range(10000):
            deque_list.append(i)
            deque_list.pop()
            
%timeit deque_list() # 10.8 s ± 218 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

여기서 timeit명령어로 시간을 측정하는데 여러 번 함수를 돌려 평균치를 계산해 준다.

 

 

Counter

여기에 elements함수와 set연산에 관련된 내용 정리하기

from collections import Counter
ball_or_strike=['B','S','S','B','B','B','S']
c=Counter(ball_or_strike)
print(c)  # Counter({'B': 4, 'S': 3})
print(list(c.elements()))  # ['B', 'B', 'B', 'B', 'S', 'S', 'S']

Counter객체에서 elements()함수를 사용하게 되면 해당 원소를 count한 값 만큼의 iterable 객체가 생성이 된다.

 

c=Counter(a=4,b=2,c=0,d=-2)
d=Counter(a=1,b=2,c=3,d=4)
print(c-d) # Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
print(c+d) # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2})
print(c&d) # Counter({'b': 2, 'a': 1})
print(c|d) # Counter({'a': 4, 'd': 4, 'c': 3, 'b': 2})

Counter객체에 대해서 Set의 연산들도 지원하고 있다.

 

 

map대신

def f(x):
    return x+5
ex=[1,2,3,4,5]
list(map(f,ex))   #[6, 7, 8, 9, 10]
print([f(value) for value in ex])  #[6, 7, 8, 9, 10]

요즘에는 map대신에 comprehesion을 사용하면 만들 수 있고 더 코드 이해가 쉽기때문에 map사용을 지양한다.

 

 

데이터 메모리

import sys
result=[1,2,3,4,5]
sys.getsizeof(result) #104

 

 

키워드 가변인자

def asterisk_test(a, b, c, d, e=0):
    print(a, b, c, d, e)


data = {"d":1 , "c":2, "b":3}
asterisk_test(10, **data)   # asterisk_test(10,d=1,c=2,b=3)

**을 함수의 인자로 넣게되면 dict형의 자료형을 위와 같이 풀어서 넣는 효과이다.

 

 

피어세션

  • 코드리뷰-번갈아 가면서

camelCase에서 seperator 없는 split 은 무엇인가 -> list()

not any( elem != '_' for elem in list )

if __name__ == "__main__":
	unittest.main()

import 할때도 파일은 실행이 되지만 위 구문은 실행되지 않는다.

프로그램의 시작점일 때만 실행

+ Recent posts