/MIT_OCW_6dot00/classes_methods_9.py
Python | 217 lines | 154 code | 9 blank | 54 comment | 12 complexity | c7275cdd201838b0aede7aa0640455d9 MD5 | raw file
- # 6.00 Problem Set 9
- #
- # Name: Rob Tsai
- # Collaborators:
- # Time:
- from string import *
- class Shape(object):
- def area(self):
- raise AttributeException("Subclasses should override this method.")
- class Square(Shape):
- def __init__(self, h):
- """
- h: length of side of the square
- """
- self.side = float(h)
- def area(self):
- """
- Returns area of the square
- """
- return self.side**2
- def __str__(self):
- return 'Square with side ' + str(self.side)
- def __eq__(self, other):
- """
- Two squares are equal if they have the same dimension.
- other: object to check for equality
- """
- return type(other) == Square and self.side == other.side
- class Circle(Shape):
- def __init__(self, radius):
- """
- radius: radius of the circle
- """
- self.radius = float(radius)
- def area(self):
- """
- Returns approximate area of the circle
- """
- return 3.14159*(self.radius**2)
- def __str__(self):
- return 'Circle with radius ' + str(self.radius)
- def __eq__(self, other):
- """
- Two circles are equal if they have the same radius.
- other: object to check for equality
- """
- return type(other) == Circle and self.radius == other.radius
- #
- # Problem 1: Create the Triangle class
- #
- ## TO DO: Implement the `Triangle` class, which also extends `Shape`.
- class Triangle(Shape):
- def __init__(self, base, height):
- self.base = float(base)
- self.height = float(height)
- def area(self):
- return self.base * self.height / 2
- def __str__(self):
- return 'Triangle with base ' + str(self.base) + ' and height ' + str(self.height)
- def __eq__(self, other):
- return type(other) == Triangle and ((self.base == other.base and self.height == other.height) or (self.base == other.height and self.height == other.base))
- #
- # Problem 2: Create the ShapeSet class
- #
- ## TO DO: Fill in the following code skeleton according to the
- ## specifications.
- class ShapeSet:
- def __init__(self):
- """
- Initialize any needed variables
- """
- self.shapeLibrary = [] #create blank list for shapeLibrary
- self.index = -1 #create index for iterator, start at -1, because next adds 1
- def addShape(self, sh):
- """
- Add shape sh to the set; no two shapes in the set may be
- identical
- sh: shape to be added
- """
- ## TO DO
- newShape = True
- for i in range(len(self.shapeLibrary)):
- if self.shapeLibrary[i] == sh:
- print "This shape already exists in library"
- newShape = False
- break
- if newShape:
- self.shapeLibrary.append(sh)
- def __iter__(self):
- """
- Return an iterator that allows you to iterate over the set of
- shapes, one shape at a time
- """
- ## TO DO
- return self
- def next(self):
- if self.index == len(self.shapeLibrary) - 1:
- raise StopIteration
- self.index += 1
- return self.shapeLibrary[self.index]
- def __str__(self):
- """
- Return the string representation for a set, which consists of
- the string representation of each shape, categorized by type
- (circles, then squares, then triangles)
- """
- ## TO DO
- shapeList = [Circle, Square, Triangle] #create list of shapes in order of category
- listOrdered = [] #initialize ordered output list
- outputString = "" # initialize output string
- for outerLoop in shapeList:
- counter = len(self.shapeLibrary)
- for i in range(counter):
- if type(self.shapeLibrary[i]) == outerLoop: #check shape type to group them
- listOrdered.append(self.shapeLibrary[i])
- for j in listOrdered: #now take ordered list and create output string
- outputString += str(j) + '\n'
- return outputString
- #
- # Problem 3: Find the largest shapes in a ShapeSet
- #
- def findLargest(shapes):
- """
- Returns a tuple containing the elements of ShapeSet with the
- largest area.
- shapes: ShapeSet
- """
- ## TO DO
- shapesToCompare = shapes
- maxVal = 0
- outputList = []
- outputTuple = ()
- counter = len(shapes.shapeLibrary)
- for i in range(counter):
- if shapes.shapeLibrary[i].area() > maxVal:
- maxVal = shapes.shapeLibrary[i].area()
- outputList = [] #initialize list again, in case it has more than one member
- outputList.append(shapes.shapeLibrary[i]) #create list of one member
- elif shapes.shapeLibrary[i].area() == maxVal:
- outputList.append(shapes.shapeLibrary[i])
- outputTuple = tuple(outputList)
- return outputTuple
- #
- # Problem 4: Read shapes from a file into a ShapeSet
- #
- def readShapesFromFile(filename):
- """
- Retrieves shape information from the given file.
- Creates and returns a ShapeSet with the shapes found.
- filename: string
- """
- ## TO DO
- shapeOut = ShapeSet()
- inputFile = open(filename)
- for line in inputFile:
- tempTuple = line.split(',')
- if tempTuple[0] == 'circle':
- shapeOut.addShape(Circle(tempTuple[1]))
- elif tempTuple[0] == 'square':
- shapeOut.addShape(Square(tempTuple[1]))
- elif tempTuple[0] == 'triangle':
- shapeOut.addShape(Triangle(tempTuple[1], tempTuple[2]))
- return shapeOut
- ## TESTS
- ##test adding shapes
- ss = ShapeSet()
- ss.addShape(Triangle(1.2, 2.5))
- ss.addShape(Circle(4))
- ss.addShape(Square(3.6))
- ss.addShape(Triangle(1.6, 6.4))
- ss.addShape(Circle(2.2))
- ##
- ##
- ### test iterator function
- print "testing __iter__ method for ShapeSet class"
- for i in ss:
- print i
- print "\n"
- #test print function for ShapeSet class
- print "testing __str__ method for ShapeSet class"
- print ss
- ## test findLargest function
- print "Testing findLargest function on first ShapeSet"
- largest = findLargest(ss)
- for e in largest:
- print e
- print "\n"
- ## test multiple shapes with same largest area
- ss = ShapeSet()
- ss.addShape(Triangle(3,8))
- ss.addShape(Circle(1))
- ss.addShape(Triangle(4,6))
- print "Testing findLargest function on second ShapeSet"
- largest = findLargest(ss)
- for e in largest:
- print e
- print "\n"
- ## test readShapesFromFile
- print "Testing readShapeFromFile"
- shapeOut = readShapesFromFile("shapes.txt")
- print shapeOut