美文网首页
python 实现一个hashmap

python 实现一个hashmap

作者: 热血大桃子 | 来源:发表于2020-07-09 17:00 被阅读0次
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    @Author:_defined
    @Time:  2020/7/9 16:41
    @Description:  实现一个hashmap
    """
    
    
    class LinearMap(object):
        """
        桶,链地址法
        """
    
        def __init__(self):
            self.items = []
    
        def add(self, k, v):
            self.items.append((k, v))
    
        def get(self, key):
            for k, v in self.items:
                if key == k:
                    return v
            raise KeyError
    
    
    class BetterMap(object):
        def __init__(self, size=16):
            self.map = [LinearMap() for _ in range(size)]
    
        def find_map(self, k):
            index = hash(k) & (len(self.map)-1)
            return self.map[index]
    
        def add(self, k, v):
            m = self.find_map(k)
            m.add(k, v)
    
        def get(self, k):
            m = self.find_map(k)
            return m.get(k)
    
    
    class HashMap(object):
        def __init__(self):
            self.maps = BetterMap()
            self.size = 0
            self.max_size = 1 << 30
    
        def resize(self):
            if self.max_size < (self.size << 1):
                return 0
            new_maps = BetterMap(self.size << 1)
            for m in self.maps.map:
                for k, v in m.items:
                    new_maps.add(k, v)
            self.maps = new_maps
            return 1
    
        def get(self, k):
            return self.maps.get(k)
    
        def add(self, k, v):
            if self.size == int(len(self.maps.map)*0.75):
                status = self.resize()
                if not status: raise Exception('Maximum space limit exceeded')
            self.maps.add(k, v)
            self.size += 1
    
    
    if __name__ == '__main__':
        import string
        hashmap = HashMap()
        for k, v in enumerate(string.ascii_letters):
            hashmap.add(k, v)
        print(hashmap)
    

    相关文章

      网友评论

          本文标题:python 实现一个hashmap

          本文链接:https://www.haomeiwen.com/subject/gjuscktx.html