首页 > 编程语言 > 详细

python 散列表查找

时间:2018-09-22 10:07:39      阅读:157      评论:0      收藏:0      [点我收藏+]
class HashTable:
    def __init__(self, size):
        self.elem = [None for i in range(size)]  
        self.count = size  #
 
    def hash(self, key):
        return key % self.count  # 
 
    def insert_hash(self, key):

        address = self.hash(key)  # 
        while self.elem[address]:  # 
            address = (address+1) % self.count  #
        self.elem[address] = key  #
 
    def search_hash(self, key):
   
        star = address = self.hash(key)
        while self.elem[address] != key:
            address = (address + 1) % self.count
            if not self.elem[address] or address == star:  # 
                return False
        return True
 
 

list_a = [12, 67, 56, 16, 25, 37, 22, 29, 15, 47, 48, 34]
hash_table = HashTable(12)
for i in list_a:
	hash_table.insert_hash(i)

for i in hash_table.elem:
	if i:
		print((i, hash_table.elem.index(i)), end=" ")
print("n")

print(hash_table.search_hash(15))
print(hash_table.search_hash(33))

  

python 散列表查找

原文:https://www.cnblogs.com/sea-stream/p/9689125.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!