拉链法实现字典

拉链法实现字典_第1张图片
拉链法.png

solts = []
solts_num = 32
for _ in range(solts_num):
solts.append([])
def put(solts, key, value):
i = hash(key) % solts_num
p = -1
for p, (k,v) in enumerate(solts[i]):
if k == key:
break
else:
solts[i].append((key, value))
return
if p >= 0:
solts[i][p] = (key, value)
def get(solts, key):
i = hash(key) % solts_num
for k , v in solts[i]:
if k == key:
return v
raise KeyError(k)

put(solts, 'r', 2)

put(solts, 'r', 2)

class Dict:
def init(self,num):
self.solts = []
self.num = num
for _ in range(num):
self.solts.append([])

def put(self, key, value):
    i = hash(key) % self.num
    for p, (k,v) in enumerate(self.__solts__[i]):
        if k == key:
            break
    else:
        self.__solts__[i].append((key, value))
        return
    self.__solts__[i][p] = (key, value)

def get(self, key):
    i = hash(key) % self.num
    for k, v in self.__solts__[i]:
        if k == key:
            return v
        raise KeyError(key)

d = dict(32)

d.put('r', 2)

d.put('d', 2)

你可能感兴趣的:(拉链法实现字典)