mirror of
https://github.com/bikini/patchwork
synced 2026-06-27 08:08:41 +00:00
48 lines
1.1 KiB
Python
48 lines
1.1 KiB
Python
from collections import deque
|
|
|
|
class Shape:
|
|
|
|
def __init__(self, name: str):
|
|
self.name = name
|
|
|
|
def describe(self) -> str:
|
|
return f'shape<{self.name}>'
|
|
|
|
def area(self) -> float:
|
|
raise NotImplementedError
|
|
|
|
class Rect(Shape):
|
|
|
|
def __init__(self, w: float, h: float):
|
|
super().__init__('rect')
|
|
self.w = w
|
|
self.h = h
|
|
|
|
def area(self) -> float:
|
|
return self.w * self.h
|
|
|
|
class Circle(Shape):
|
|
|
|
def __init__(self, r: float):
|
|
super().__init__('circle')
|
|
self.r = r
|
|
|
|
def area(self) -> float:
|
|
return 3.14159265 * self.r * self.r
|
|
|
|
def total_area(shapes):
|
|
q = deque(shapes)
|
|
total = 0.0
|
|
while q:
|
|
s = q.popleft()
|
|
try:
|
|
total += s.area()
|
|
except NotImplementedError:
|
|
continue
|
|
return total
|
|
if __name__ == '__main__':
|
|
shapes = [Rect(3, 4), Circle(5), Rect(1, 1), Circle(2)]
|
|
for s in shapes:
|
|
print(s.describe(), '->', round(s.area(), 4))
|
|
print('total area:', round(total_area(shapes), 4))
|