Python實現Map資料結構
阿新 • • 發佈:2019-02-08
class HashTable: def __init__(self): # 初始化兩個list,一個用來儲存鍵值,一個用來儲存值 self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size # 定義Hash函式,使用餘數法 def hashFunction(self, key, size): return (key % size) # 定義線性探測hash函式 def rehash(self, oldhash, size): return (oldhash + 1) % size # 插入鍵值對 def put(self, key, data): # 得到Hash值 hashvalue = self.hashFunction(key, len(self.slots)) # 查詢當前hash值對應位置的鍵值是否為空,為空則插入 if self.slots[hashvalue] == None: self.slots[hashvalue] = key self.data[hashvalue] = data # 不為空則更新 else: if self.slots[hashvalue] == key: self.data[hashvalue] = data else: # 否則繼續查詢下一個位置,這裡使用線性探測器去解決Hash衝突問題 nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None and self.slots[nextslot] != key: nextslot = self.rehash(nextslot, len(self.slots)) if self.slots[nextslot] == None: self.slots[nextslot] = key self.data[nextslot] = data else: self.data[nextslot] = data # 過載Python的magic函式 def __getitem__(self, key): return self.get(key) # 過載Python的magic函式 def __setitem__(self, key, data): self.put(key, data) # 拿鍵值方法和存放方法一樣 def get(self, key): startslot = self.hashFunction(key, len(self.slots)) data = None flag = False stop = False pos = startslot while self.slots[startslot] != None and not flag and not stop: if self.slots[pos] == key: flag = True data = self.data[pos] else: pos = self.rehash(pos, len(self.slots)) if pos == startslot: stop = True return data if __name__ == '__main__': H = HashTable() H[54] = 'cat' H[26] = 'dog' H[93] = 'lion' H[17] = 'tiger' H[77] = 'bird' H[31] = 'cow' H[44] = 'goat' H[55] = 'pig' H[20] = 'chicken' H[8] = 'mouse' print(H.slots) print(H.data)