-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunsorted_table_map.py
More file actions
62 lines (54 loc) · 2.35 KB
/
Copy pathunsorted_table_map.py
File metadata and controls
62 lines (54 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from map_base import MapBase
class UnsortedTableMap(MapBase):
"""Map implementation using an unordered list."""
def __init__(self):
"""Create an empty map."""
self._table = [] # list of _Item's
def __getitem__(self, k):
"""Return value associated with key k (raise KeyError if not found)."""
for item in self._table:
if k == item._key:
return item._value
raise KeyError('Key Error: ' + repr(k))
def __setitem__(self, k, v):
"""Assign value v to key k, overwriting existing value if present."""
for item in self._table:
if k == item._key: # Found a match:
item._value = v # reassign value
return # and quit
# did not find match for key
self._table.append(self._Item(k,v))
def __delitem__(self, k):
"""Remove item associated with key k (raise KeyError if not found)."""
for j in range(len(self._table)):
if k == self._table[j]._key: # Found a match:
self._table.pop(j) # remove item
return # and quit
raise KeyError('Key Error: ' + repr(k))
def __len__(self):
"""Return number of items in the map."""
return len(self._table)
def __iter__(self):
"""Generate iteration of the map's keys."""
for item in self._table:
yield item._key # yield the KEY