執行:
Python 內建 (built-in) 的 sets 分為兩種:
__hash__
自定義哈希。python 透過 hashset 來實現 set,減少運行的時間 (O(n^2) -> O(n))
class HashSet:
def __init__(self, contents = []):
self.items = [None] * 10
self.numItems = 0
for item in contents:
self.add(item)
當想將 3 以及 -7 放入長度為 10 的哈希表時,因為 3 與 -7 除 10 後的所得的餘數都是 3,如果都作為它們的 index 會有衝突 (collision)。
Linear Probing:
def __add(item, items):
idx = hash(item) % len(items)
loc=-1
while items[idx] != None:
if items[idx] == item:
# item already in set
return False
if loc < 0 and type(items[idx]) == HashSet.__Placeholder:
loc = idx
idx = (idx + 1) % len(items)
if loc < 0:
loc = idx
items[loc] = item
return True
載荷因子 (load factor) = 填入表中的元素個數 / len(Hash)
一個高的載荷因子代表可以更有效的運用空間,但同時衝突的機率也更高。
rehashing:當載荷因子 > 75 %,新請求空間將現有的 hash 表移動到更大的 hash 表。
時間複雜度:O(1)。
def __rehash(oldList, newList):
for x in oldList:
if x != None and type(x) != HashSet.__Placeholder:
HashSet.__add(x,newList)
return newList
def add(self, item):
if HashSet.__add(item,self.items):
self.numItems += 1
load = self.numItems / len(self.items)
if load >= 0.75:
self.items = HashSet.__rehash(self.items,[None]*2*len(self.items))