UnsortedMapsOfLists.py: from UnsortedTableMap import UnsortedTableMap class UnsortedMapOfLists(UnsortedTableMap):     def __getitem__(self, position: tuple):         # Write a comment here to explain why we need this if statement         if len(position) == 1:             return super().__getitem__(position)         key, index = position         head: list = super().__getitem_

Computer Networking: A Top-Down Approach (7th Edition)
7th Edition
ISBN:9780133594140
Author:James Kurose, Keith Ross
Publisher:James Kurose, Keith Ross
Chapter1: Computer Networks And The Internet
Section: Chapter Questions
Problem R1RQ: What is the difference between a host and an end system? List several different types of end...
icon
Related questions
Question

The UnsortedTableMap class is located in the maps folder. In the attachment, you will find a partially implemented class called UnsortedMapOfLists, which extends UnsortedTableMap. The values associated with the keys in UnsortedMapOfLists are arrays. So you have an array with each key. Off course you can save an array in the value of UnsortedTableMap class without the class we are going to develop, but our class makes this easier, as it allows using a syntax like this:

myMap["somekey", 1] to reach element at index 1 in the array associated with key "somekey". I already implemented methods __setitem__ and __getitem__. Your task is to:

  1. implement method __delitem__ . Deletion will be performed for an element in the array. If index is not given, delete the array associated with the key.
  2. implement a function (not a method in the class) to swap the arrays associated with two given keys.
  3. Add the required comment in method __getitem__.
  4. implement a main to verify that your code is working properly. You can decide how to do that.

 

All of these go in the same file.

UnsortedMapsOfLists.py:

from UnsortedTableMap import UnsortedTableMap

class UnsortedMapOfLists(UnsortedTableMap):

    def __getitem__(self, position: tuple):
        # Write a comment here to explain why we need this if statement
        if len(position) == 1:
            return super().__getitem__(position)

        key, index = position

        head: list = super().__getitem__(key)

        if index >= len(head):
            raise IndexError("Size of array associated with key: ", key, " is: ", len(head))
        return head[index]

    def __setitem__(self, position: tuple, value):

        if len(position) == 1:
            super().__setitem__(position, value)
            return

        key, index = position
        try:
            head: list = super().__getitem__(key)
            if index < len(head):
                # overrite exiting value, or append
                head[index] = value
            elif index == len(head):
                head.append(value)
            else:
                raise IndexError("Size of array associated with key: ", key, " is: ", len(head))

        except KeyError:
            # new key, create a list for the key
            head = [value]
            self._table.append(self._Item(key, head))

    def __delitem__(self, position: tuple):
        """Remove item associated with key k and index, if index not given, remove the item (array)
        associated with the key
          raise KeyError if not found
          raise IndexError if index out of bound
          """
        raise Exception("Implement me")


m = UnsortedMapOfLists()
m["a", 0] = 5
m['a', 0] = 50
m['a', 1] = 60
m['b', 0] = 2
m['c', 1] = 10
m['d'] = [10, 20, 30]
print(m['a', 0])
print(m['a', 1])
print(m['b', 0])
print(m['a'])
print(m['d'])

### Test with the following after you implement the required methods
#del m['b', 0]
#del m['c']

(if needed, here are two modules that support UnsortedMapOfLists.py)

UnsortedTableMap.py:

from MapBase 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

MapBase.py:

from collections import MutableMapping

class MapBase(MutableMapping):

#------------------------------- nested _Item class -------------------------------
class _Item:
    """Lightweight composite to store key-value pairs as map items."""
    __slots__ = '_key', '_value'

    def __init__(self, k, v):
      self._key = k
      self._value = v

    def __eq__(self, other):
      return self._key == other._key   # compare items based on their keys

    def __ne__(self, other):
      return not (self == other)       # opposite of __eq__

    def __lt__(self, other):
      return self._key < other._key    # compare items based on their keys

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps with 1 images

Blurred answer
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Computer Networking: A Top-Down Approach (7th Edi…
Computer Networking: A Top-Down Approach (7th Edi…
Computer Engineering
ISBN:
9780133594140
Author:
James Kurose, Keith Ross
Publisher:
PEARSON
Computer Organization and Design MIPS Edition, Fi…
Computer Organization and Design MIPS Edition, Fi…
Computer Engineering
ISBN:
9780124077263
Author:
David A. Patterson, John L. Hennessy
Publisher:
Elsevier Science
Network+ Guide to Networks (MindTap Course List)
Network+ Guide to Networks (MindTap Course List)
Computer Engineering
ISBN:
9781337569330
Author:
Jill West, Tamara Dean, Jean Andrews
Publisher:
Cengage Learning
Concepts of Database Management
Concepts of Database Management
Computer Engineering
ISBN:
9781337093422
Author:
Joy L. Starks, Philip J. Pratt, Mary Z. Last
Publisher:
Cengage Learning
Prelude to Programming
Prelude to Programming
Computer Engineering
ISBN:
9780133750423
Author:
VENIT, Stewart
Publisher:
Pearson Education
Sc Business Data Communications and Networking, T…
Sc Business Data Communications and Networking, T…
Computer Engineering
ISBN:
9781119368830
Author:
FITZGERALD
Publisher:
WILEY