class ListMap:
"""Map ADT stored in two parallel lists: simple, but slow when large."""
def __init__(self):
self._keys = []
self._values = []
def put(self, key, value):
if key in self._keys:
self._values[self._keys.index(key)] = value
else:
self._keys.append(key)
self._values.append(value)
def get(self, key, default=None):
if key in self._keys:
return self._values[self._keys.index(key)]
return default
def keys(self):
return list(self._keys)
class DictMap:
"""The same Map ADT, stored in a Python dict (a hash table): fast."""
def __init__(self):
self._d = {}
def put(self, key, value):
self._d[key] = value
def get(self, key, default=None):
return self._d.get(key, default)
def keys(self):
return list(self._d)
def count_words(text, counts):
"""Count words using ANY map object that offers put, get and keys."""
for word in text.lower().split():
counts.put(word, counts.get(word, 0) + 1)
return counts
poem = "Snow on snow on snow"
for empty_map in [ListMap(), DictMap()]:
m = count_words(poem, empty_map)
pairs = []
for k in m.keys():
pairs.append((k, m.get(k)))
print(type(m).__name__, pairs)
maps.py: two implementations of one ADT, and a client that works with both.