[从头学数学] 第250节 Python实现数据结构:映射(HashMap, Dict)

来源:互联网 发布:天敏t2网络机顶盒 编辑:程序博客网 时间:2024/05/16 07:26
剧情提要:
阿伟看到了一本比较有趣的书,是关于《计算几何》的,2008年由北清派出版。很好奇
它里面讲了些什么,就来看看啦。

正剧开始:
星历2016年07月27日 12:47:25, 银河系厄尔斯星球中华帝国江南行省。

[工程师阿伟]正在和[机器小伟]一起研究[计算几何]]。




HashMap的内核是一个HashSet,必须要以集合类作为先锋。



这些图都是相当随意找的,关于字典的图有很多,但多少都不单纯是字典。


<span style="font-size:18px;">#### @usage   映射# @author  mw# @date    2016年07月27日  星期三  12:55:20 # @param# @return####class HashMap:    def info(self):        s = '[';        for x in self:            s += str(x)+'->'+str(self[x])+', ';        if (len(s) > 2):            s = s[:-2];        s += ']';        print(s);    def __iter__(self):        for x in self.hSet:            yield x.getKey()    def __len__(self):        return len(self.hSet)        class __KVPair:        def __init__(self,key,value):            self.key = key            self.value = value        def __eq__(self,other):            if type(self) != type(other):                return False            return self.key == other.key        def getKey(self):            return self.key        def getValue(self):            return self.value        def __hash__(self):            return hash(self.key)    #初始化    def __init__(self):        #self.hSet = hashset.HashSet()        self.hSet = HashSet();    def __contains__(self,item):        return HashMap.__KVPair(item,None) in self.hSet    def not__contains__(self,item):        return item not in self.hSet    def __setitem__(self,key,value):        self.hSet.add(HashMap.__KVPair(key,value))    def __getitem__(self,key):        if HashMap.__KVPair(key,None) in self.hSet:            val = self.hSet[HashMap.__KVPair(key,None)].getValue()            return val        raise KeyError("Key " + str(key) + " not in HashMap")    def create(self, contents = []):        for i in range(len(contents)):            self[i] = contents[i];    def pop(self, key):        del self[key];                        def get(self, key):        if HashMap.__KVPair(key,None) in self.hSet:            return self[key];        else:            return 'No Record';    def __delitem__(self, key):        if HashMap.__KVPair(key,None) in self.hSet:            self.hSet.remove(HashMap.__KVPair(key,None));        else:            raise KeyError("Item not in HashMap")            def keys(self):        keys = [];        for x in self:            keys.append(x);        return keys;    def values(self):        values = [];        for x in self:            values.append(self[x]);        return values;    def items(self):        items = [];        for x in self:            items.append([x, self[x]]);        return items;    #随机弹出元素    def popitem(self):        result = [];        for x in self:            result.append([x, self[x]]);            self.pop(x);            return result;    def setdefault(self, key, default = None):        if HashMap.__KVPair(key,None) in self.hSet:            self.hSet.remove(HashMap.__KVPair(key,None));        self[key] = default;        def clear(self):        for x in self:            self.pop(x);                #把原来的字典用新字典更新    def update(self, newdict):        for x in self:            if x in newdict:                self.setdefault(x, newdict[x]);    #浅拷贝    def copy(self):        return self;</span>


用例:

<span style="font-size:18px;">def main():    #计时开始    startTime = time.clock();    hashmap = HashMap();    dict_ = [['师父', '唐三藏'], ['大徒弟', '孙悟空'], ['二徒弟', '猪悟能'], ['三徒弟', '沙悟净'], ['座骑', '白龙马']];    for i in range(len(dict_)):        hashmap[dict_[i][0]] = dict_[i][1];    hashmap.info();    print(len(hashmap));    hashmap.create(dict_);    hashmap.info();    hashmap.pop(1);    hashmap.info();    print('--keys--');    print(hashmap.keys());    print('--values--');    print(hashmap.values());    print('--items--');    print(hashmap.items());        #hashmap.pop(8); #抛异常    del hashmap['师父'];    hashmap.info();    #del hashmap['师父'];#抛异常    a = hashmap.popitem();    print(a);    hashmap.info();    hashmap.setdefault(0);    hashmap.setdefault(3);    hashmap.info();    hashmap.setdefault(0, 'OK');    hashmap.info();    map2 = HashMap();    map2.create(dict_);    hashmap.update(map2);    hashmap.info();    map3 = hashmap.copy();    map3.info();    map3.pop('大徒弟');    map3.info();    hashmap.info();        #计时结束    endTime = time.clock();    #打印结果    print('操作用时:{0:.3e} s'.format(endTime-startTime));</span>




本节到此结束,欲知后事如何,请看下回分解。

0 0
原创粉丝点击