Hash Tables: Hash functions, Sets & Maps

Minsu Kang·2025년 1월 24일
post-thumbnail

필기
1페이지

2페이지
업로드중..

실제 예시

# Hashsets
s = set()
print(s)

Add

# Add item into Set > O(1)
s.add(1)
s.add(2)
s.add(3)

print(s)

{1, 2, 3}

Look up

# Lookup if item in set > *O(1)
if 1 in s:
	print(True)

Remove

# Remove Item > O(1)
s.remove(3)

print(s)

{1, 2}

중복된 string

string = "aaaabbbbbbbbbbbbbcccccccceeeeaa"
sett = set(string) #Set construction O(S)

print(sett)

{'a', 'b', 'c', 'e'}

이러면 sett에서 unique한 것만 남음

# Hash mpas - Dictionaries
d = {
	'm' : 1,
    's' : 2,
    'r' : 3}

{'m' : 1,'s' : 2, 'r' : 3}

# Look up 할 수 있음
if 'm' not in d:
	print(False)

print(d['m']) #이건 'm'이 dictionary 안에 있다고 가정함

Loop over dictionary items!

# Loop over the key:val pairs of the dictionary: O(n)
for key, val in d.items():
	print[f'key {key}:val {val}']

Default dict

from collections import defaultdict

default = defaultdict(int)
default[2]

0

기본 정수, 0을 채운 default dictionary를 생성함. 그래서 key가 없는 지 찾아볼 필요 없이 0을 반환함

from collections import defaultdict

default = defaultdict(list)
default[2]

[]

[] 리스트로 채워진 dictionary 생성

Counter

from collections import Counter

string # 'aaaaabbbbccccceeeeee'
counter = Counter(string)

print(counter)

Counter({'a' : 5, 'b' : 4, 'c': 5, 'e' : 6})
요소의 갯수를 세는 dictionary 반환!

profile
안녕하세요! 강민수입니다.

0개의 댓글