1. 程式人生 > >python hash演算法實現

python hash演算法實現

#!/usr/bin/env python
# -*- coding:utf-8 -*-


class HashTable:
    def __init__(self, size):
        self.elem = [None for i in range(size)]  # 使用list資料結構作為雜湊表元素儲存方法
        self.count = size  # 最大表長

    def hash(self, key):
        return key % self.count  # 雜湊函式採用除留餘數法

    def insert_hash(self, key)
:
print key """插入關鍵字到雜湊表內""" address = self.hash(key) # 求雜湊地址 print address while self.elem[address] != None: # 當前位置已經有資料了,發生衝突。 address = (address+1) % self.count # 線性探測下一地址是否可用 print address self.elem[address] = key # 沒有衝突則直接儲存。
print self.elem 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 if __name__ == '__main__': list_a = [0, 12, 67, 56, 16, 25, 37, 22, 29, 15, 47, 48, 34] hash_table = HashTable(len(list_a)) 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))) print(hash_table.search_hash(15)) print(hash_table.search_hash(33))