PageRenderTime 37ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/MIT_OCW_6dot00/classes_methods_9.py

https://github.com/robtsai/mathrocks
Python | 217 lines | 154 code | 9 blank | 54 comment | 12 complexity | c7275cdd201838b0aede7aa0640455d9 MD5 | raw file
  1. # 6.00 Problem Set 9
  2. #
  3. # Name: Rob Tsai
  4. # Collaborators:
  5. # Time:
  6. from string import *
  7. class Shape(object):
  8. def area(self):
  9. raise AttributeException("Subclasses should override this method.")
  10. class Square(Shape):
  11. def __init__(self, h):
  12. """
  13. h: length of side of the square
  14. """
  15. self.side = float(h)
  16. def area(self):
  17. """
  18. Returns area of the square
  19. """
  20. return self.side**2
  21. def __str__(self):
  22. return 'Square with side ' + str(self.side)
  23. def __eq__(self, other):
  24. """
  25. Two squares are equal if they have the same dimension.
  26. other: object to check for equality
  27. """
  28. return type(other) == Square and self.side == other.side
  29. class Circle(Shape):
  30. def __init__(self, radius):
  31. """
  32. radius: radius of the circle
  33. """
  34. self.radius = float(radius)
  35. def area(self):
  36. """
  37. Returns approximate area of the circle
  38. """
  39. return 3.14159*(self.radius**2)
  40. def __str__(self):
  41. return 'Circle with radius ' + str(self.radius)
  42. def __eq__(self, other):
  43. """
  44. Two circles are equal if they have the same radius.
  45. other: object to check for equality
  46. """
  47. return type(other) == Circle and self.radius == other.radius
  48. #
  49. # Problem 1: Create the Triangle class
  50. #
  51. ## TO DO: Implement the `Triangle` class, which also extends `Shape`.
  52. class Triangle(Shape):
  53. def __init__(self, base, height):
  54. self.base = float(base)
  55. self.height = float(height)
  56. def area(self):
  57. return self.base * self.height / 2
  58. def __str__(self):
  59. return 'Triangle with base ' + str(self.base) + ' and height ' + str(self.height)
  60. def __eq__(self, other):
  61. return type(other) == Triangle and ((self.base == other.base and self.height == other.height) or (self.base == other.height and self.height == other.base))
  62. #
  63. # Problem 2: Create the ShapeSet class
  64. #
  65. ## TO DO: Fill in the following code skeleton according to the
  66. ## specifications.
  67. class ShapeSet:
  68. def __init__(self):
  69. """
  70. Initialize any needed variables
  71. """
  72. self.shapeLibrary = [] #create blank list for shapeLibrary
  73. self.index = -1 #create index for iterator, start at -1, because next adds 1
  74. def addShape(self, sh):
  75. """
  76. Add shape sh to the set; no two shapes in the set may be
  77. identical
  78. sh: shape to be added
  79. """
  80. ## TO DO
  81. newShape = True
  82. for i in range(len(self.shapeLibrary)):
  83. if self.shapeLibrary[i] == sh:
  84. print "This shape already exists in library"
  85. newShape = False
  86. break
  87. if newShape:
  88. self.shapeLibrary.append(sh)
  89. def __iter__(self):
  90. """
  91. Return an iterator that allows you to iterate over the set of
  92. shapes, one shape at a time
  93. """
  94. ## TO DO
  95. return self
  96. def next(self):
  97. if self.index == len(self.shapeLibrary) - 1:
  98. raise StopIteration
  99. self.index += 1
  100. return self.shapeLibrary[self.index]
  101. def __str__(self):
  102. """
  103. Return the string representation for a set, which consists of
  104. the string representation of each shape, categorized by type
  105. (circles, then squares, then triangles)
  106. """
  107. ## TO DO
  108. shapeList = [Circle, Square, Triangle] #create list of shapes in order of category
  109. listOrdered = [] #initialize ordered output list
  110. outputString = "" # initialize output string
  111. for outerLoop in shapeList:
  112. counter = len(self.shapeLibrary)
  113. for i in range(counter):
  114. if type(self.shapeLibrary[i]) == outerLoop: #check shape type to group them
  115. listOrdered.append(self.shapeLibrary[i])
  116. for j in listOrdered: #now take ordered list and create output string
  117. outputString += str(j) + '\n'
  118. return outputString
  119. #
  120. # Problem 3: Find the largest shapes in a ShapeSet
  121. #
  122. def findLargest(shapes):
  123. """
  124. Returns a tuple containing the elements of ShapeSet with the
  125. largest area.
  126. shapes: ShapeSet
  127. """
  128. ## TO DO
  129. shapesToCompare = shapes
  130. maxVal = 0
  131. outputList = []
  132. outputTuple = ()
  133. counter = len(shapes.shapeLibrary)
  134. for i in range(counter):
  135. if shapes.shapeLibrary[i].area() > maxVal:
  136. maxVal = shapes.shapeLibrary[i].area()
  137. outputList = [] #initialize list again, in case it has more than one member
  138. outputList.append(shapes.shapeLibrary[i]) #create list of one member
  139. elif shapes.shapeLibrary[i].area() == maxVal:
  140. outputList.append(shapes.shapeLibrary[i])
  141. outputTuple = tuple(outputList)
  142. return outputTuple
  143. #
  144. # Problem 4: Read shapes from a file into a ShapeSet
  145. #
  146. def readShapesFromFile(filename):
  147. """
  148. Retrieves shape information from the given file.
  149. Creates and returns a ShapeSet with the shapes found.
  150. filename: string
  151. """
  152. ## TO DO
  153. shapeOut = ShapeSet()
  154. inputFile = open(filename)
  155. for line in inputFile:
  156. tempTuple = line.split(',')
  157. if tempTuple[0] == 'circle':
  158. shapeOut.addShape(Circle(tempTuple[1]))
  159. elif tempTuple[0] == 'square':
  160. shapeOut.addShape(Square(tempTuple[1]))
  161. elif tempTuple[0] == 'triangle':
  162. shapeOut.addShape(Triangle(tempTuple[1], tempTuple[2]))
  163. return shapeOut
  164. ## TESTS
  165. ##test adding shapes
  166. ss = ShapeSet()
  167. ss.addShape(Triangle(1.2, 2.5))
  168. ss.addShape(Circle(4))
  169. ss.addShape(Square(3.6))
  170. ss.addShape(Triangle(1.6, 6.4))
  171. ss.addShape(Circle(2.2))
  172. ##
  173. ##
  174. ### test iterator function
  175. print "testing __iter__ method for ShapeSet class"
  176. for i in ss:
  177. print i
  178. print "\n"
  179. #test print function for ShapeSet class
  180. print "testing __str__ method for ShapeSet class"
  181. print ss
  182. ## test findLargest function
  183. print "Testing findLargest function on first ShapeSet"
  184. largest = findLargest(ss)
  185. for e in largest:
  186. print e
  187. print "\n"
  188. ## test multiple shapes with same largest area
  189. ss = ShapeSet()
  190. ss.addShape(Triangle(3,8))
  191. ss.addShape(Circle(1))
  192. ss.addShape(Triangle(4,6))
  193. print "Testing findLargest function on second ShapeSet"
  194. largest = findLargest(ss)
  195. for e in largest:
  196. print e
  197. print "\n"
  198. ## test readShapesFromFile
  199. print "Testing readShapeFromFile"
  200. shapeOut = readShapesFromFile("shapes.txt")
  201. print shapeOut