利用python语言初始化一个哈希表 HashTable。利用除留余数法构建哈希西数,并使用开放地址法解决冲突,将关键字为(12,9,15,10.8.21, 3,29,30,11,40.7的序列次存入哈希表中。 使用哈希表查找的算法查找关键字为15的数据元素
时间: 2023-06-25 21:02:39 浏览: 178
以下是使用Python语言实现的哈希表HashTable:
```python
class HashTable:
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def hashfunction(self, key):
return key % self.size
def rehash(self, oldhash):
return (oldhash + 1) % self.size
def put(self, key, data):
hashvalue = self.hashfunction(key)
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue)
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot)
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def get(self, key):
startslot = self.hashfunction(key)
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position)
if position == startslot:
stop = True
return data
```
接下来,我们可以按照题目要求,将关键字为(12,9,15,10.8.21, 3,29,30,11,40.7的序列次存入哈希表中:
```python
H = HashTable(11)
H.put(12, 'Twelve')
H.put(9, 'Nine')
H.put(15, 'Fifteen')
H.put(10, 'Ten')
H.put(8, 'Eight')
H.put(21, 'Twenty-One')
H.put(3, 'Three')
H.put(29, 'Twenty-Nine')
H.put(30, 'Thirty')
H.put(11, 'Eleven')
H.put(40, 'Forty-Seven')
```
最后,我们可以使用哈希表查找的算法查找关键字为15的数据元素:
```python
print(H.get(15))
```
运行结果为:
```
Fifteen
```
说明我们成功地在哈希表中找到了关键字为15的数据元素。
阅读全文