해시테이블

이동규 (Justin)·2020년 6월 15일
0

데이터 스트럭처

목록 보기
1/4
post-thumbnail

파이썬으로 구현하였다

class HashTable:
  def __init__(self, table_size):
    self.size = table_size
    self.hash_table = [0 for a in range(self.size)]

  def getKey(self,data):
    self.key = ord(data[0]) # ord는 아스키코드 반환
    return self.key

  def hashFunction(self,key):
    return key % self.size
  
  def getAddress(self,key):
    myKey = self.getKey(key)
    hash_address = self.hashFunction(myKey)
    return hash_address

  def save(self, key, value):
    hash_address = self.getAddress(key)
    self.hash_table[hash_address] = value

  def read(self,key):
    hash_address = self.getAddress(key)
    return self.hash_table[hash_address] 

  def delete(self,key):
    hash_address = self.getAddress(key)

    if self.hash_table[hash_address] != 0:
      self.hash_table[hash_address] = 0
      return True
    else:
      return False


#Test Code

mytable = HashTable(8)
mytable.save('a','1111')
mytable.save('b','3333')
mytable.save('c','5555')
mytable.save('d','8888')

print(mytable)
print(mytable.hash_table)

print(mytable.read('d'))
print(mytable.delete('c'))
print(mytable.hash_table)
profile
Frontend Developer, JamStack, Ethereum

0개의 댓글