CS 345 Homework 3

Due Monday Feb 6 at 9pm. Upload to Desire 2 Learn dropbox for homework 3.

Python Primer 3 solution

Description

For this programming assignment, you are going to design and implement a class that partially replicates the behavior of the python class Set. Your set can store any data type that can be hashed.

From python …

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Requirements

  • Your set class CANNOT use python’s set class but it must behave like the python set class… HINT: you could use the dict class (creatively) or roll your own hash value list.

  • Your set class must implement the following methods:
    • __init__(self) contructor should take an optional list argument to initialize the internal data structure. If no argument is provided, the set is initially empty.

    • __repr__(self) Returns a string representation of the set.

    • add(elem) Add element elem to the set only if it is unique to the set.

    • addSeq(self, seq) Add contents of seq to the set where each item in contents is unique to the set.

    • remove(self, elem) Removes and returns the element elem from the set. Raises KeyError if elem is not contained in the set.

    • get(self, elem) Returns element elem from the set. Raises KeyError if elem is not contained in the set.

    • clear(self) Remove all elements from the set.

    • size(self) Returns the size of the set.

  • You will need to write your own test cases for your class that TEST all methods! For example, at the bottom of your class definition you would have the following (plus more tests of course!):
if __name__ == '__main__':
	setobj = MySet([6, 8, 3, 6])
	print setobj
	# Should print something like 3, 6, 8 (note the uniqueness of 6?)

What to Turn In?

  • Your single class definition file following the naming conventions required in the syllabus.

Example try/exception and raise error snippets.

mylist = [2, 4, 6, 8]

def getVal(q):
	for i in mylist:
		if i == q:
			return i
	raise KeyError


""" Demonstrates how one might handle different exceptions."""
data = {'j': 8, 'h': 9}
key = None
try: 
	key = raw_input('Enter a key:')
	v1 = data[key] # will throw key error b/c key may not exist in data yet.
	val = key + 2; # will throw type error b/c strings cannot be added to ints.

except KeyError:
	data[key] = 1 # Create a new key and assign a 1 if key error was thrown.
	v1 = data[key]
	print key, 'now created in ', data
	
except TypeError:
	val = key + str(2)  # Not really interesting but this HANDLES it...
	print val



""" Demonstrates calling a function getVal() that may throw or raise an error """
try:
	getVal(7)
except KeyError:
	print '7 not found in list. :('

Example Class Definition for a class named City

# city.py

class City:

    def __init__(self, n='No Name', c=[], p=0):
        self.name = n
        self.cars = c
        self.population = p

    def __repr__(self):
        hdr = '\n' + self.name + '\nCARS: ' + str(len(self.cars)) + ' ' + 'POPULATION: ' + str(self.population)
        body = '******************************\n'
        for i in self.cars:
            body += str(i) + '\n'
        
        return hdr + '\n' + body

    def getPopulation(self):
        return self.population

    def setPopulation(self, p):
        self.population = p

    def deactivateAllCars(self):
        for i in self.cars:
            i.stop()


"""Tests for City class"""

if __name__ == '__main__':
    city = City(n='Testville', c=['ford', 'chevy'], p=2)
    print 'A city object was created:'
    print city

    city.setPopulation(90000)
    
    if city.getPopulation() == 90000:
        print "success"
    else:
        print 'epic fail'

    print 'City object now:'
    print city

Solution

# solution.py

class Hw3set:
	""" A class the mimics the behavior of python's built in Set class. A set is represented as a list in this implementation."""

	def __init__(self, d=[]):
		self.__data = []
		self.addSeq(d)

	def __repr__(self):
		"""Returns a string representation of the set."""
		s = ', '.join([str(i) for i in self.__data])
		return s


	def add(self, elem):
		"""Add element elem to the set only if it is unique to the set."""
		for i in self.__data:
			if i == elem:
				return None # found existing value. Exit.
		
		self.__data.append(elem)

	def addSeq(self, seq):
		"""Add contents of seq to the set where each item in contents is unique to the set."""
		for i in seq:
			self.add(i)

	def remove(self, elem):
		"""Removes and returns the element elem from the set. Raises KeyError if elem is not contained in the set."""
		try:
			self.__data.remove(elem)
		
		except:
			raise KeyError

	def get(self, elem):
		"""Returns element elem from the set. Raises KeyError if elem is not contained in the set."""
		try:
			return self.__data[self.__data.index(elem)]
		
		except ValueError:
			raise KeyError
	
	def clear(self):
		"""Remove all elements from the set."""
		self.__data = []

	def size(self):
		"""Returns the size of the set."""
		return len(self.__data)

# End of class Hw3set

"""Test Hw3set methods"""
if __name__=="__main__":
	testset = Hw3set([6, 8, 3, 6])
	print testset, '\t==>', 'Hw3set object initialized'

	testset.add(8)
	print testset, '\t==>', 'No change. Value exists in set.'

	testset.add(9)
	print testset, '\t==>', 'Set updated with new value, 9.'

	try:
		testset.remove(9)
		print testset, '\t==>', 'Set updated with value 9 removed.'
	except:
		print testset, '\t==>', 'Removal of 9 failed. Value not in set.'

	try:
		val = testset.get(21)
		print val, '\t\t==>', 'Successfully retrieved.'
	except:
		print testset, '\t==>', 'Retrieval of 21 failed. Value not in set.'

	try:
		val = testset.get(6)
		print val, '\t\t==>', 'Successfully retrieved.'
	except:
		print testset, '\t==>', 'Retrieval of 6 failed. Value not in set.'

	testset.addSeq([7, 8, 9])
	print testset, '\t==>', 'Set updated with seq [7, 8, 9].'

	if testset.size() == 5:
		print testset, '\t==>', 'Set length:', testset.size()
	else:
		print testset, '\t==>', 'Fail. Set length:', testset.size(), 'Should be 5.'

	testset.clear()

	if testset.size() == 0:
		print testset, '\t\t==>', 'Set is empty. Set length:', testset.size()
	else:
		print testset, '\t==>', 'Fail. Set length:', testset.size(), 'Should be 0.'

	testset.add(77)
	print testset, '\t\t==>', 'Set updated with new value, 77.'

	if testset.size() == 1:
		print testset, '\t\t==>', 'Set length:', testset.size()
	else:
		print testset, '\t\t==>', 'Fail. Set length:', testset.size(), 'Should be 1.'

© 2017 - . All rights reserved
Built using Jekyll