Docsity

Abstract Data Type - Data Structures - Lecture Notes, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
1. The Map/Dictionary abstract data type (ADT) stores key-value pairs. The key is used to look up the data value.
Returns a string representation of the dictionary
__s
tr
__(self
)
str(d)
Returns the number of items in the dictionary
__len__(self)len(d)
Iterates over the keys in the dictionary
__iter__(self)for k in d:
Return
True
if
key
is in the dictionary; return
False
otherwise
__contains__(self,key)if ”Name” in d:
Removes the entry associated with
key
__
del
item__(self,
key)
d
el
d
[”Name”]
Given a
key
return it value or
None
if
key
is not
in the dictionary
__
g
key)
temp =
d[”Name”]
Inserts a key-value entry if
key
does not exist or
replaces the old value with
value
if
key
exists.
__setitem__(self,
key,value)
d[”Name”]
= “Bob”
Constructs an empty dictionary
__init__(self)d = ListDict()
DescriptionClass NameMethod call
a) Complete the code for the
__contains__
method.
def __contains__(self, key):
b) Complete the code for the
__setitem__
method.
def __setitem__(self, key, value):
Data Structures Lecture 15 Name:__________________
Lecture 15 Page 1
from entry import Entry
class ListDict(object):
"""Dictionary implemented with a Python list."""
def __init__(self):
self._table = []
def __getitem__(self, key):
"""Returns the value associated with key or
returns None if key does not exist."""
entry = Entry(key, None)
try:
index = self._table.index(entry)
return self._table[index].getValue()
except:
return None
def __delitem__(self, key):
"""Removes the entry associated with key."""
entry = Entry(key, None)
try:
index = self._table.index(entry)
self._table.pop(index)
except:
return
def __str__(self):
"""Returns string repr. of the dictionary"""
resultStr = "{"
for item in self._table:
resultStr = resultStr + " " + str(item)
return resultStr + " }"
def __iter__(self):
"""Iterates over keys of the dictionary"""
for item in self._table:
yield item.getKey()
raise StopIteration
ListDict
object
_table
_key _value
. . .
012345
Python list object
Entry object
Name Bob
class Entry(object):
"""A key/value pair."""
def __init__(self, key, value):
self._key = key
self._value = value
def getKey(self):
return self._key
def getValue(self):
return self._value
def setValue(self, newValue):
self._value = newValue
def __eq__(self, other):
if not isinstance(other, Entry):
return False
return self._key == other._key
def __str__(self):
return str(self._key) + ":" + str(self._value)
Docsity.com
pf2

Partial preview of the text

Download Abstract Data Type - Data Structures - Lecture Notes and more Study notes Data Structures and Algorithms in PDF only on Docsity!

1. The Map/Dictionary abstract data type (ADT) stores key-value pairs. The key is used to look up the data value.

str(d) str(self) Returns a string representation of the dictionary

len(d) len(self) Returns the number of items in the dictionary

for k in d: iter(self) Iterates over the keys in the dictionary

Return True if key is in the dictionary; return

False otherwise

if ”Name” in d: contains(self,key)

del d[”Name”] delitem(self,key) Removes the entry associated with key

Given a key return it value or None if key is not

in the dictionary

temp = d[”Name”] getitem(self,key)

Inserts a key-value entry if key does not exist or

replaces the old value with value if key exists.

d[”Name”] = “Bob” setitem(self,key,value)

d = ListDict() init(self) Constructs an empty dictionary

Method call Class Name Description

a) Complete the code for the contains method.

def contains(self, key):

b) Complete the code for the setitem method.

def setitem(self, key, value):

Data Structures Lecture 15 Name:__________________

Lecture 15 Page 1

from entry import Entry

class ListDict(object): """Dictionary implemented with a Python list."""

def init(self): self._table = []

def getitem(self, key): """Returns the value associated with key or returns None if key does not exist.""" entry = Entry(key, None) try: index = self._table.index(entry) return self._table[index].getValue() except: return None

def delitem(self, key): """Removes the entry associated with key.""" entry = Entry(key, None) try: index = self._table.index(entry) self._table.pop(index) except: return

def str(self): """Returns string repr. of the dictionary""" resultStr = "{" for item in self._table: resultStr = resultStr + " " + str(item) return resultStr + " }"

def iter(self): """Iterates over keys of the dictionary""" for item in self._table: yield item.getKey() raise StopIteration

ListDict

object

_table

_key _value

Python list object

Entry object

Name Bob

class Entry(object): """A key/value pair."""

def init(self, key, value): self._key = key self._value = value

def getKey(self): return self._key

def getValue(self): return self._value

def setValue(self, newValue): self._value = newValue

def eq(self, other): if not isinstance(other, Entry): return False return self._key == other._key

def str(self): return str(self._key) + ":" + str(self._value)

Docsity.com

2. Dictionary implementation using hashing with chaining -- an UnorderedList object at each slot in the hash table.

a) In getitem , why is the

entry = Entry(key, None) object created?

b) In getitem , where does self._index

receive its value?

c) What single modification was needed to

the UnorderedList‘s remove method?

d) Complete the iter method.

Data Structures Lecture 15 Name:__________________

Lecture 15 Page 2

from entry import Entry from unordered_linked_list import UnorderedList

class ChainingDict(object): """Dictionary implemented using hashing with chaining."""

def init(self, capacity = 8): self._capacity = capacity self._table = [] for index in range(self._capacity): self._table.append(UnorderedList()) self._size = 0 self._index = None

def contains(self, key): """Returns True if key is in the dictionary or False otherwise.""" self._index = abs(hash(key)) % self._capacity entry = Entry(key, None)

return self._table[self._index].search(entry)

def getitem(self, key): """Returns the value associated with key or returns None if key does not exist.""" if key in self: entry = Entry(key, None) entry = self._table[self._index].remove(entry) self._table[self._index].add(entry) return entry.getValue() else: return None

def delitem(self, key): """Removes the entry associated with key.""" entry = Entry(key, None) if key in self: entry = Entry(key, None) entry = self._table[self._index].remove(entry) self._size -= 1

def setitem(self, key, value): """Inserts an entry with key/value if key does not exist or replaces the existing value with value if key exists.""" entry = Entry(key, value) if key in self: entry = self._table[self._index].remove(entry) entry.setValue(value) else: self._size += 1 self._table[self._index].add(entry)

def len(self): return self._size

def str(self): result = "HashDict: capacity = " +
str(self._capacity) + ", load factor = " +
str(len(self) / self._capacity) for i in range(self._capacity): result += "\nRow " + str(i)+": "+str(self._table[i]) return result

def iter(self): """Iterates over the keys of the dictionary"""

ChainingDict Object

_capacity

_size

_table _index

Python list of UnorderList objects containing Entrys

Docsity.com