
직접 코드로 구현해보자!
hash_table = list([i for i in range(10)]) print(hash_table) # [0,1,2,3,4,5,6,7,8,9]
def hash_func(key): return key % 5
이제 해쉬 테이블에 저장해보자.
data1 = 'changhyeon' data2 = 'choi' data3 = 'star' data4 = 'bucks' print(ord(data1[0]), ord(data2[0]), ord(data3[0])) # 99 99 115 print(ord(data1[0]), hash_func(ord(data1[0]))) # 99 4 print(ord(data1[0]), ord(data4[0])) # 99 98
!해쉬 테이블 값 저장 예시
def storage_data(data, value): key = ord(data[0]) hash_address = hash_func(key) hash_table[hash_address] = value storage_data('changhyeon', '19950807')
!데이터 읽어보기
def get_data(data): key = ord(data[0]) hash_address = hash_func(key) print(hash_table[hash_address]) get_data('changhyeon') # 19950807
리스트 변수를 활용해서 해쉬 테이블을 구현해보자!
hash_table = list([0 for i in range(8)]) print(hash_table) #[0, 0, 0, 0, 0, 0, 0, 0] def get_key(data): return hash(data) get_key('changhyeon') # -470506737412036400 def hash_func(key): return key % 8 def save_data(data, value): hash_address = hash_func(get_key(data)) hash_table[hash_address] = value def read_data(data): hash_address = hash_func(get_key(data)) print(hash_address) print(hash_table[hash_address]) save_data('changhyeon', '01091616424') save_data('ch', '01012345678') read_data('changhyeon') #4 #01012345678 read_data('ch') #4 # 01012345678 print(hash_table) #[0, 0, 0, 0, '01012345678', 0, 0, 0]