python: hashable type

hyyyynjnยท2021๋…„ 12์›” 12์ผ
0

python ์ •๋ฆฌ

๋ชฉ๋ก ๋ณด๊ธฐ
22/26
post-thumbnail
post-custom-banner

python์˜ hashable type
๐Ÿ‘‰ int , float , str , tuple , frozenset and NoneType

๋งŒ์•ฝ tuple ์›์†Œ ์ค‘ unhashable type์˜ ์›์†Œ๊ฐ€ ์žˆ๋‹ค๋ฉด ํ•ด๋‹น tuple์€ unhashable ์ด๋‹ค.

>>> t1 = (10, 'A', frozenset([1, 2, 3])) 
>>> t2 = (10, 'A', {1, 2, 3}) 
>>> hash(t1)  # OK! 
1315572702399614049 
>>> hash(t2)  # NOT OK! 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unhashable type: 'set'

set์€ hashable type์˜ ์›์†Œ๋งŒ ๋‹ด์„ ์ˆ˜ ์žˆ๋‹ค.
๐Ÿ‘‰ tuple (o) , list(x)

a = set()
a.add((1, 2))
print(a) # {(1, 2)}

set์— list๋ฅผ addํ•  ์ˆ˜ ์—†๋‹ค.

a = set()
a.add([1, 2])

์—๋Ÿฌ ๋ฐœ์ƒ
Traceback (most recent call last):
  File "C:\Users\guswn\PycharmProjects\Algorithm\interview.py", line 347, in <module>
    a.add([1, 2])
TypeError: unhashable type: 'list'

Set elements as well as dictionary keys have to be hashable
๐Ÿ‘‰ set์˜ ์›์†Œ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ dict์˜ key๊ฐ’๋„ hashable type์˜ ๊ฐ’์ด ๋“ค์–ด๊ฐ€์•ผํ•œ๋‹ค.

key๊ฐ’์œผ๋กœ tuple์ด ๊ฐ€๋Šฅํ•˜๋‹ค

a = dict()
a[(1, 2)] = 1
print(a) # {(1, 2): 1}

key๊ฐ’์œผ๋กœ list๋Š” ์•ˆ๋œ๋‹ค

a = dict()
a[[1, 2]] = 1

์—๋Ÿฌ ๋ฐœ์ƒ
Traceback (most recent call last):
  File "C:\Users\guswn\PycharmProjects\Algorithm\interview.py", line 347, in <module>
    a[[1,2]] = 1
TypeError: unhashable type: 'list'
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€