[ create a new paste ] login | about

Link: http://codepad.org/IKKx062f    [ raw code | output | fork ]

Asix3 - Python, pasted on Feb 14:
# 6.00 Problem Set 9
#
# Name:
# Collaborators:
# Time:

from string import *
import string

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=6.0, height=9.0):
        """
        base = base of triangle, height = height of triangle
        """
        self.base = float(base)
        self.height = float(height)
    def area(self):
        """
        returns area of triangle
        """
        return .5 * self.base * self.height
    def __str__(self):
        return "Triangle with base " + str(self.base) +" and height "+ str(self.height)
    def __eq__(self, other):
        """
        if same base & height, returns true
        if other has smaler area, returns true
        """
        return type(other) == Triangle and self.base == other.base and self.height == other.height

#
# Problem 2: Create the ShapeSet class
#
## TO DO: Fill in the following code skeleton according to the
##    specifications.

class ShapeSet(object):
    def __init__(self):
        """
        Initialize any needed variables
        """
        ## members in the set
        self.members = []
        self.circles = []
        self.squares = []
        self.triangles = []
        ## for __iter__ -- see lecture handout
        self.place = None
    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
        ## check that shape to be addes is of correct type and not
        ## already in set
        # type doesn't return superclasses
        if sh in self.members: raise ValueError('duplicate shape')
        if type(sh) == Circle: self.circles.append(sh)
        elif type(sh) == Square: self.squares.append(sh)
        elif type(sh) == Triangle: self.triangles.append(sh)
        else: raise TypeError('not a known shape')
        ## add shape to members
        self.members = self.circles + self.squares + self.triangles
    def __iter__(self):
        """
        Return an iterator that allows you to iterate over the set of
        shapes, one shape at a time
        """
        ## TO DO
        ## don't really understand this
        self.place = 0
        return self
    
    ## see lecture handout for next definition
    def next(self):
        if self.place >= len(self.members):
            raise StopIteration
        self.place += 1
        return self.members[self.place-1]
    
    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
        setString = ''
        for n in self:
            setString += str(n) + '\n'
        return setString

        
#
# 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
    maxArea = max(n.area() for n in shSet)
    maxList = []
    for n in shSet:
        if n.area() == maxArea:
            maxList.append(n)
    return tuple(maxList)
        

#
# 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
    inputFile = open(filename)
    fileShSet = ShapeSet()
    for line in inputFile:
        lSplit = string.split(string.strip(line),',')
        if lSplit[0] == 'triangle':
            fileShSet.addShape(Triangle(float(lSplit[1]), float(lSplit[2])))
        elif lSplit[0] == 'circle':
            fileShSet.addShape(Circle(float(lSplit[1])))
        elif lSplit[0] == 'square':
            fileShSet.addShape(Square(float(lSplit[1])))
        else: print lSplit[0] + " is not a supported shape."
    return fileShSet

## for debugging

sq1 = Square(5)
sq2 = Square(3)
cr1 = Circle(5)
tr1 = Triangle(4,7)
tr2 = Triangle(4,9)
shSet = ShapeSet()
shSet.addShape(sq1)
shSet.addShape(sq2)
shSet.addShape(cr1)
shSet.addShape(tr1)
shSet.addShape(tr2)
print shSet


Output:
1
2
3
4
5
6
Circle with radius 5.0
Square with side 5.0
Square with side 3.0
Triangle with base 4.0 and height 7.0
Triangle with base 4.0 and height 9.0



Create a new paste based on this one


Comments: