해쉬 테이블 (Hash Table)
1. 해쉬 구조
Hash Table : 키(Key)에 데이터(Value)를 저장하는 데이터 구조
- Key를 통해 바로 데이터를 받아올 수 있으므로, 속도가 획기적으로 빨라진다.
- 파이썬 딕셔너리(Dictionaray) 타입이 해쉬 테이블의 예이다.
2. 알아둘 용어
- 해쉬(Hash) : 임의의 값을 고정 길이로 변환하는 것
- 해쉬 테이블(Hash Table) : 키 값의 연산에 의해 직접 접근이 가능한 데이터 구조
- 해싱 함수(Hashing Function) : Key에 대해 산술 연산을 이용해 데이터 위치를 찾을 수 있는 함수
- 해쉬 값(Hash Value) 또는 해쉬 주소(Hash Address) : Key를 해싱 함수로 연산해서, 해쉬 값을 알아내고, 이를 기반으로 해쉬 테이블에서 해당 Key에 대한 데이터 위치를 일관성 있게 찾음
- 슬롯(Slot) : 한 개의 데이터를 저장할 수 있는 공간
- 저장할 데이터에 대해 Key를 추출할 수 있는 별도 함수도 존재할 수 있다.
3. 간단한 해쉬 예
3.1 hash table 만들기
hash_talbe = list([0 for in range(10)])
3.2 hash function 만들기 (가장 간단한 방식인 Division)
def hash_func(key):
return key % 5
3.3 hash table에 데이터 저장
data1 = 'Andy'
data2 = 'Dave'
data3 = 'Trump'
## ord() : 문자의 ASCII 코드 리턴
print(ord(data1[0]), ord(data2[0]), ord(data3[0]))
def storage_data(data, value):
key = ord(data[9])
hash_address = hash_func(key)
hash_table[hash_address] = value
3.4 해쉬 테이블에서 특정 주소의 데이터를 가져오는 함수
storage_data('Andy', '01055553333')
storage_data('Dave', '01033333333')
storage_data('Trunp', '01044443333')
3.5 실제 데이터를 저장하고 읽기
def get_data(data):
key = ord(data[0])
hash_address = hash_func(key)
hash_table[hash_address] = value
4. 자료구조 해쉬 테이블의 장단점과 주요 용도
장점
- 데이터 저장/읽기 속도가 빠르다.
- 해쉬는 키에 대한 데이터가 있는지 (중복) 확인이 쉽다.
단점
- 일반적으로 저장 공간이 좀 더 많이 필요하다.
- 여러 키에 해당하는 주소가 동일할 경우 충돌을 해결하기 위한 자료구조가 필요하다.
주요 용도
- 검색이 많이 필요한 경우
- 저장, 삭제, 읽기가 빈번한 경우
- 캐쉬 구현시 (중복 확인이 쉽기 때문)
5. 프로그래밍
hash_table = list([0 for i in range(8)])
def get_key(data):
return hash(data)
def hash_function(key):
return key % 8
def save_data(data, value):
hash_address = hash_function(get_key(data))
hash_table[hash_address] = value
def read_data(data):
hash_address = hash_function(get_key(data))
return hash_table[hash_address]
6. 충동 (Collision) 해결 알고리즘 (좋은 해쉬 함수 사용)
6.1 Chaining 기법
: 개방 해싱 또는 Open Hasing 기법 중 하나 : 하나의 테이블 저장 공간 외의 공간을 활용하는 기법
: 충돌이 일어나면, 링크드 리스트라는 자료 구조를 사용해서, 링크드 리스트로 데이터를 추가로 뒤에 연결시켜 저장
hash_table = list([0 for i in range(8)])
def get_key(data):
return hash(data)
def hash_function(key):
return key % 8
def save_data(data, value):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(len(hash_table[hash_address])):
if hash_table[hash_address][index][0] == index_key:
hash_table[hash_address][index][1] = value
return
hash_table[hash_address].append([index_key, value])
else:
hash_table[hash_address] = [[index_key, value]]
def read_data(data):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(len(hash_table[hash_address])):
if hash_table[hash_address][index][0] == index_key:
return hash_talbe[hash_address][index][1]
return None
else:
return None
return hash_table[hash_address]
6.2 Linear Probing 기법
: 폐쇄 해싱 또는 Close Hashing 기법 중 하나 : 해쉬 테이블 저장 공간 안에서 충돌 문제 해결
: 충돌이 일어난다면, 해당 hash address의 다른 address 부터 맨 처음 나오는 빈 공간에 저장
hash_table = list([0 for i in range(8)])
def get_key(data):
return hash(data)
def hash_function(key):
return key % 8
def save_data(data, value):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
hash_table[index] = [index_key, value]
return
elif hash_table[index][0] == index_key:
hash_table[index][1] = value
return
def read_data(data):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
return None
elif hash_talbe[index][0] == index_key:
return hash_table[index][1]
else:
return None
6.3 빈번한 충돌을 개선하는 기법
: 해쉬 함수를 재정의 및 테이블 저장공간을 확대
[참고] 해쉬 함수와키 생성 함수
SHA-1
import hashlib
data = 'test'.encode()
hash_object = hashlib.sha1()
hash_object.update(data)
hex_dig = hash_object.hexdigest()
print(hex_dig)
import hashlib
hash_table = list([0 for i in range(8)])
def get_key(data):
hash_object = hashlib.sha256()
hash_object.update(data.encode())
hex_dig = hash_object.hexdigest()
return int(hex_dig, 16)
def hash_function(key):
return key % 8
def save_data(data, value):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
hash_table[index] = [index_key, value]
return
elif hash_table[index][0] == index_key:
hash_table[index][1] = value
return
def read_data(data):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
return None
elif hash_talbe[index][0] == index_key:
return hash_table[index][1]
else:
return None
7. 시간 복잡도
일반적인 경우 = 충돌이 없는 경우 : \(O(1)\)
최악의 경우 = 충돌이 전부 일어나는 경우 : \(O(n)\)
'Python > 알고리즘 & 자료구조' 카테고리의 다른 글
[Python] 힙 (Heap) 정리 및 구현 (0) | 2022.08.02 |
---|---|
트리 (Tree) (0) | 2022.08.02 |
링크드 리스트 (Linked List) (0) | 2022.08.02 |
스택 (Stack) (0) | 2022.08.02 |
큐 (Queue) (0) | 2022.08.02 |