【纪录】Hash about

backup a easy implement

# coding: utf-8


def add(k, v):
    pass


def get(target):
    pass


class LinearMap(object):
    """线性表结构"""
    def __init__(self):
        self.items = []

    def add(self, k, v):
        self.items.append((k, v))

    def get(self, k):
        for key, val in self.items:
            if key == k:
                return val
        raise KeyError


class BetterMap(object):
    """利用 LinearMap 对象作为子表,建立更快的查询表"""
    def __init__(self, n=100):
        self.maps = []          # 总表格
        for i in range(n):
            self.maps.append(LinearMap())

    def find_map(self, k):
        index = hash(k) % len(self.maps)
        return self.maps[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(2)
        self.num = 0

    def get(self, k):
        return self.maps.get(k)

    def add(self,k, v):
        if self.num == len(self.maps.maps):
            self.resize()
        self.maps.add(k, v)
        self.num += 1

    def resize(self):
        new_maps = BetterMap(self.num * 2)
        for m in self.maps.maps:
            for k, v in m.items:
                new_maps.add(k, v)

        self.maps = new_maps

 

Reference:

https://www.cnblogs.com/hanahimi/p/4765265.html  hash 表学习笔记

http://python.jobbole.com/86522/?utm_source=blog.jobbole.com&utm_medium=relatedPosts  Python源码分析-PyDictObject

https://www.nosuchfield.com/2016/07/29/the-python-implementationp-of-HashTable/  HashTable 的 Python 实现

https://harveyqing.gitbooks.io/python-read-and-write/content/python_advance/python_dict_implementation.html  Python字典实现

posted @ 2018-10-26 19:24  piperck  阅读(179)  评论(0编辑  收藏  举报