Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class HashMap:
- """HashMap class"""
- def __init__(self, size):
- self.size = size
- self.map = [[] for x in range(size)]
- def hashkey(self, key):
- """interne hashfunction uses the python hashfunction
- args: the key that needs hashing as string
- return: the hashvalue
- examples: there are no examples because the hash function is random
- each time...
- """
- return hash(key) % self.size
- def insert (self, key, value):
- """Insert the given key (given as a string) with the given value (given as
- an integer)
- args: key as string, and value as int
- return : not return value, it just updates the HashMap with the new value at location key
- examples:
- >>> h = HashMap(6)
- >>> h.insert('foo', 69)
- """
- if (type(key)!= str or type(value) != int):
- raise TypeError ('type value hat to be int and of key str')
- else:
- hash_key = self.hashkey(key)
- if self.map[hash_key]:
- sp = False
- for i, pair in enumerate(self.map[hash_key]):
- if(pair[0]==key):
- self.map[hash_key][i] = (key, value)
- sp = False
- break
- if not sp:
- self.map[hash_key].append((key, value))
- else:
- self.map[hash_key].append((key, value))
- def lookup(self, key):
- """ lookup method for the objects of the class HashTable
- args: key given as string
- return: value of the given key as int or 0 if key not in self.HT
- examples:
- »> h = HashTable(5)
- »> h.insert('name', 69)
- »> h.lookup('name')
- 69
- »> h.lookup("aaa")
- 0
- """
- hash_key = self.hashkey(key)
- for elem in self.map[hash_key]:
- if elem[0] == key:
- return elem[1]
- return 0
- if __name__=="__main__":
- def test_hashMap():
- # just a little test function...doctstrings are ok but I preffer test
- # functions when it comes to objects...
- HashMap(5).insert("name", 2)
- HashMap(5).insert("NAME", 2)
- HashMap(5).insert("etc", 5)
- HashMap(5).insert("qdmhs", 21)
- HashMap(5).insert("ddd", 1)
- HashMap(5).insert("mbnd", 10)
- assert HashMap(5).lookup("A.Merkel") == 0
- assert HashMap(5).lookup("qdmhs") == 21
- assert HashMap(5).lookup("name") == 2
- Hash.Map(5).insert("name", 69)
- assert HashMap(5).lookup("name") == 69
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement