Python:使用链接实现地图

时间:2015-06-08 04:57:02

标签: python dictionary data-structures

我的任务是通过创建一个包含两个列表的哈希表来实现带链接的映射,一个名为“slots”,另一个名为“data”。我的代码似乎一直工作到'G'字符。我无法确定这里发生了什么,我尝试过调试。

class HashTable:
    def __init__(self):
        self.size = 11
        self.slots = [None] * self.size
        self.data = [None] * self.size

    def put(self,key,data):
        hashvalue = self.hashfunction(key,len(self.slots))

        if self.slots[hashvalue] == None:
            self.slots[hashvalue] = list()
            self.slots[hashvalue].append(key)
            self.data[hashvalue] = list()
            self.data[hashvalue].append(data)
        else:
            if self.slots[hashvalue] != None:
                self.data[hashvalue].append(data)  #replace

    def hashfunction(self,key,size):
         return key%size


    def get(self,key):
        startslot = self.hashfunction(key,len(self.slots))

        data = None
        stop = False
        found = False
        position = startslot
        while self.slots[position] != None and not found and not stop:
            for index in range (len(self.slots[position])):
                if self.slots[position][index]== key:
                    found = True
                    data = self.data[position][index]
                    break
            position+1
            if position == startslot:
                stop = True
        return data

    def __getitem__(self,key):
        return self.get(key)

    def __setitem__(self,key,data):
        self.put(key,data)

## TEST FOR HashTable
h = HashTable() # create new hash table

nums = [1, 3, 5, 50, 1000] # some keys
nums = nums + [ len(h.slots)*i for i in range(20)] # some keys that have same hash
vals = [ chr(x) for x in range(ord('A'),ord('Z')) ] # list of single letters from A to Z

# add key/values
for i in range(len(nums)):
    # print("adding (%d, %s)"%(nums[i],vals[i]),end=" ")
    h[nums[i]] = vals[i]

for i in range(len(nums)):
    key = nums[i]
    value = vals[i]
    gotValue = h[key]
    assert gotValue == value,"expected key: %d to lookup value: %s but got value %s instead " % (key, value, gotValue)

print("\nAll TESTS PASSED")

1 个答案:

答案 0 :(得分:0)

我发现了我的问题

我忘了在下面添加一行:

if self.slots[hashvalue] != None:

将键添加到插槽的[hashvalue]。 所以现在我有:

if self.slots[hashvalue] != None:
            self.slots[hashvalue].append(key)
            self.data[hashvalue].append(data)

它将数据值添加到相应的列表“data”,但不是匹配的键值到列表“slots”