May 2017
Intermediate to advanced
310 pages
8h 5m
English
Using the put() and get() methods doesn't look very good, however. We want to be able to treat our hash table as a list, that is, we would like to be able to use ht["good"] instead of ht.get("good"). This is easily done with the special methods __setitem__() and __getitem__():
def __setitem__(self, key, value): self.put(key, value) def __getitem__(self, key): return self.get(key)
Our test code can now look like this instead:
ht = HashTable() ht["good"] = "eggs" ht["better"] = "ham" ht["best"] = "spam" ht["ad"] = "do not" ht["ga"] = "collide" for key in ("good", "better", "best", "worst", "ad", "ga"): v = ht[key] print(v) print("The number of elements is: {}".format(ht.count))
Notice that we ...
Read now
Unlock full access