[Algorithms] 파이썬 자료형에 따른 시간 복잡도 (Big-O)

정은·2023년 8월 29일

Algorithms

목록 보기
3/5

BaekJoon 에서 Python으로 알고리즘 문제를 풀다보면 계속 부딪히는 문제가 있다.
바로 시간 초과 ❗

이를 해결하기 위해 무엇을 해야할까 ❓

→ 시간 복잡도를 생각하여 문제를 풀어야한다!

이때까지 편하게 사용했던 Python 함수가 알고보니 O(N)O(N) 이라면❓
당연히, 다른 언어들과 동일하게 알고리즘을 설계하였어도 시간초과가 날 수 밖에 없다.

그래서 파이썬 자료형 중 가장 많이 쓰이는 List, Set, Dictionary의 함수별 시간 복잡도를 알아보자 💡

List

OperationExampleClassNotes
Indexl[i]O(1)
Storel[i] = 0O(1)
Lengthlen(l)O(1)
Appendl.append(5)O(1)mostly: ICS-46 covers details
Popl.pop()O(1)same as l.pop(-1), popping at end
Clearl.clear()O(1)similar to l = []
Slicel[a:b]O(b-a)l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)
Extendl.extend(...)O(len(...))depends only on len of extension
Constructionlist(...)O(len(...))depends on length of ... iterable
check ==, !=l1 == l2O(N)
Insertl[a:b] = ...O(N)
Deletedel l[i]O(N)depends on i; O(N) in worst case
Containmentx in/not in lO(N)linearly searches list
Copyl.copy()O(N)Same as l[:] which is O(N)
Removel.remove(...)O(N)
Popl.pop(i)O(N)O(N-i): l.pop(0):O(N) (see above)
Extreme valuemin(l)/max(l)O(N)linearly searches list for value
Reversel.reverse()O(N)
Iterationfor v in l:O(N)Worst: no return/break in loop
Sortl.sort()O(N Log N)key/reverse mostly doesn't change
Multiplyk*lO(k N)5l is O(N): len(l)l is O(N**2)

Set

OperationExampleClassNotes
Lengthlen(s)O(1)
Adds.add(5)O(1)
Containmentx in/not in sO(1)compare to list/tuple - O(N)
Removes.remove(..)O(1)compare to list/tuple - O(N)
Discards.discard(..)O(1)
Pops.pop()O(1)popped value "randomly" selected
Clears.clear()O(1)similar to s = set()
Constructionset(...)O(len(...))depends on length of ... iterable
check ==, !=s != tO(len(s))same as len(t); False in O(1) if the lengths are different
<=/<s <= tO(len(s))issubset
>=/>s >= tO(len(t))issuperset s <= t == t >= s
UnionstO(len(s)+len(t))
Intersections & tO(len(s)+len(t))
Differences - tO(len(s)+len(t))
Symmetric Diffs ^ tO(len(s)+len(t))
Iterationfor v in s:O(N)Worst: no return/break in loop
Copys.copy()O(N)
  • Set 자료형은 리스트 자료형에 비해 O(1)O(1)의 연산이 많은 편이다.

Dictionary

OperationExampleClassNotes
Indexd[k]O(1)
Stored[k] = vO(1)
Lengthlen(d)O(1)
Deletedel d[k]O(1)
get/setdefaultd.get(k)O(1)
Popd.pop(k)O(1)
Pop itemd.popitem()O(1)popped item "randomly" selected
Cleard.clear()O(1)similar to s = {} or = dict()
Viewd.keys()O(1)same for d.values()
Constructiondict(...)O(len(...))depends # (key,value) 2-tuples
Iterationfor k in d:O(N)all forms: keys, values, items
Worst: no return/break in loop
  • Dictionary 자료형은 거의 대부분 O(1)O(1) 이란 것을 기억하자.

[References]
Complexity of Python Operations

profile
정니의 이런거 저런거 기록 일지 😛

0개의 댓글