📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division121314class LinearMap:15"""A simple implementation of a map using a list of tuples16where each tuple is a key-value pair."""1718def __init__(self):19self.items = []2021def add(self, k, v):22"""Adds a new item that maps from key (k) to value (v).23Assumes that they keys are unique."""24self.items.append((k, v))2526def get(self, k):27"""Looks up the key (k) and returns the corresponding value,28or raises KeyError if the key is not found."""29for key, val in self.items:30if key == k:31return val32raise KeyError333435class BetterMap:36"""A faster implementation of a map using a list of LinearMaps37and the built-in function hash() to determine which LinearMap38to put each key into."""3940def __init__(self, n=100):41"""Appends (n) LinearMaps onto (self)."""42self.maps = []43for i in range(n):44self.maps.append(LinearMap())4546def find_map(self, k):47"""Finds the right LinearMap for key (k)."""48index = hash(k) % len(self.maps)49return self.maps[index]5051def add(self, k, v):52"""Adds a new item to the appropriate LinearMap for key (k)."""53m = self.find_map(k)54m.add(k, v)5556def get(self, k):57"""Finds the right LinearMap for key (k) and looks up (k) in it."""58m = self.find_map(k)59return m.get(k)606162class HashMap:63"""An implementation of a hashtable using a BetterMap64that grows so that the number of items never exceeds the number65of LinearMaps.6667The amortized cost of add should be O(1) provided that the68implementation of sum in resize is linear."""6970def __init__(self):71"""Starts with 2 LinearMaps and 0 items."""72self.maps = BetterMap(2)73self.num = 07475def get(self, k):76"""Looks up the key (k) and returns the corresponding value,77or raises KeyError if the key is not found."""78return self.maps.get(k)7980def add(self, k, v):81"""Resize the map if necessary and adds the new item."""82if self.num == len(self.maps.maps):83self.resize()8485self.maps.add(k, v)86self.num += 18788def resize(self):89"""Makes a new map, twice as big, and rehashes the items."""90new_map = BetterMap(self.num * 2)9192for m in self.maps.maps:93for k, v in m.items:94new_map.add(k, v)9596self.maps = new_map979899def main():100import string101102m = HashMap()103s = string.ascii_lowercase104105for k, v in enumerate(s):106m.add(k, v)107108for k in range(len(s)):109print(k, m.get(k))110111112if __name__ == '__main__':113main()114115116