루프의 속도
물론 요소 검색에는 set이 더 적합해요. 해시를 기반으로 하기 때문에 대부분의 경우 시간 복잡도가 상수에 가깝다고 기대할 수 있어요. 하지만 객체의 모든 요소를 반복(iterate) 하는 경우는 어떨까요? pytest와 pytest-benchmark를 사용해 list와 set의 요소를 루프로 순회할 때 속도를 비교해 보세요. pytest 패키지는 이미 임포트되어 있어요.
이 연습은 강의의 일부입니다
Python 테스트 입문
연습 안내
iterate_로 시작하는 함수들 앞에@benchmark데코레이터를 추가하세요.iterate_list와iterate_set의 루프를 완성하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def test_list(benchmark):
# Add decorator here
@____
def iterate_list():
# Complete the loop here
____ in [i for i in range(1000)]:
pass
def test_set(benchmark):
# Add decorator here
____
def iterate_set():
# Complete the loop here
____ in {i for i in range(1000)}:
pass