最近在学习python, 学起来很不错,在我一个初学者的眼中,这是一门很好的脚本语言。无论学习者有没有编程经验,都可以很好的学习。当然,要想学好,做练习是必不可少的。一些简单的练习,我就不再说了。在这里,我想从学习新语言的同时,正好把忘了的数据结构好好补补。因此,现在我准备实现一个hashmap,只是完成最基础的功能。毕竟,本人也是菜鸟一个,如果写的有误,请指正,勿喷哈。希望与正在学习python的朋友共同学习,交流
下面是我的代码实现
# -*- coding: cp936 -*- #--------------------------------------------- # #author chile #version 1.0 #date 2014-01-11 #desc 使用hash实现一个映射容器 ,只有简单的实现 # # #--------------------------------------------- class entry: def __init__(self,key = None,val = None,_next = ''): self.before = None self.key = key self.value = val self.next = _next class hashmap(): def __init__(self,length = 16): self.len = length self.arr = self.initarr(length) self.entry = entry() def hashcode(self,key): return abs(hash(key)) % self.len def put(self,key,value): index = self.hashcode(key) root = self.arr[index] self.entry = entry(key = key,val = value) self.putentry(root, key) self.arr[index] = root def putentry(self,entry,key): if isinstance(entry.next,str): entry.next = self.entry else: self.putentry(entry.next, key) def get(self,key): index = self.hashcode(key) entry = self.arr[index] if isinstance(entry.next,str): return None return self.getentry(entry.next, key) def remove(self,key): index = self.hashcode(key) root = self.arr[index] if not isinstance(root.next,str): self.removeentry(root, key) def initarr(self,len): arr = [] for v in range(0,len): arr.append(entry()) return arr def getentry(self,entry,key): _key = entry.key if cmp(key,_key) == 0: return entry.value else: self.getentry(entry.next, key) def removeentry(self,entry,key): next = entry.next if cmp(next.key,key) == 0: entry.next = next.next else: self.removeentry(next,key) mymap = hashmap() mymap.put('2', 22) mymap.put('3', 'vals') mymap.put('5', 'val5s') mymap.put('4', 'val4s') mymap.put('6', 'val6s') mymap.put('12', 'va12l') mymap.put('13', 'va13ls') mymap.put('15', 'val15s') mymap.put('14', 'val14s') mymap.put('16', 'val16s') print mymap.get('3') print mymap.get('2') mymap.remove('4') print mymap.get('14')