جواب «Polymorphic Areas» چالش 10 از جلسهی 27
سؤال
کلاس پایهی Shape متد area() دارد که NotImplementedError بالا میآورد. زیرکلاسهای Rect(w, h)، Circle(r) (با math.pi) و Triangle(a, b, c) (فرمول هرون) آن را بازنویسی میکنند. ورودی خطبهخط مثل rect 3 4، circle 1، tri 3 4 5 است تا end؛ نوع ناشناخته را با unknown shape: <name> گزارش کنید. برای هر شکل معتبر <name>: <area با ۲ رقم اعشار> و در پایان largest: <name> (اولین شکل با بیشترین مساحت) چاپ کنید؛ اگر شکل معتبری نبود largest: none.
راهنما
هرون: s = (a+b+c)/2 و مساحت sqrt(s(s-a)(s-b)(s-c)). اعداد را float کنید و با * به سازنده بدهید.
یک جواب درست
import math
class Shape:
def area(self):
raise NotImplementedError
class Rect(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
class Triangle(Shape):
def __init__(self, a, b, c):
self.a, self.b, self.c = a, b, c
def area(self):
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
kinds = {"rect": Rect, "circle": Circle, "tri": Triangle}
best_name, best_area = "none", -1
while True:
line = input()
if line == "end":
break
name, *nums = line.split()
if name not in kinds:
print(f"unknown shape: {name}")
continue
area = kinds[name](*map(float, nums)).area()
print(f"{name}: {area:.2f}")
if area > best_area:
best_name, best_area = name, area
print(f"largest: {best_name}")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن