哈希映射实现问题 - python

时间:2015-04-08 00:00:48

标签: python hashmap

我试图在python中实现自己的哈希映射,但继续遇到insert方法的问题。 如果self.the_array [hash(item)]为None: IndexError:列表索引超出范围

class My_Hash:

def __init__(self):
    self.size = 10
    self.the_array = self.size*[None]
    self.count = 0

def __len__(self):
    return self.count

def is_empty(self):
    return len(self) == 0

def is_full(self):
    return len(self)>=len(self.the_array)

def hash(self,item):
     value= (ord(item[0]) + ord(item[1]))%self.size
     print (value)
     return value

def resize(self):
    self.size = self.size^2
    new_size = len(self.the_array)^2
    for i in new_size:
        self.the_array.append(None)

def insert(self,item):
   if self.is_full():
       self.resize()
   if self.the_array[hash(item)] is None:  #this is where the error occurs
    self.the_array[hash(item)]= item
    self.count+=1
   else:
       new_hash = hash(item)
       hash_attempt = 0
       while not(self.the_array[new_hash] is None):
           new_hash = ((new_hash + new_hash^2)*3)%len(self.the_array)
           hash_attempt +=1
           if hash_attempt > len(self.the_array)/2:
                self.resize()
       self.the_array[new_hash]= item

0 个答案:

没有答案