I didn't know the answer to the problem on the video, so I tried to solve it myself. I thought it would be helpful for those who are learning from the live video of Sparta Camp.
This is a beginner's problem in object-oriented programming. Rather than writing good code in object-oriented programming, the goal is to be able to write in the correct grammar.
Implement the Circle class so that the following code is correct. area means area, and perimeter means perimeter (perimeter).
circle.py
#Circle with radius 1
circle1 = Circle(radius=1)
print(circle1.area()) #3.14
print(circle1.perimeter()) #6.28
#Circle with radius 3
circle3 = Circle(radius=3)
print(circle3.area()) #28.26 ← Probably 28 in the video.27 is wrong
print(circle3.perimeter()) # 18.84 ← Probably 18 in the video.85 is wrong
#Implement the Rectangle class so that the following code works correctly
#diagonal means (the length of) the diagonal.
rectangle1 = Rectangle(height=5, width=6)
rectangle1.area() #30.00
rectangle1.diagonal() #7.81
rectangle2 = Rectangle(height=3, width=3)
rectangle2.area() #9.00
rectangle2.diagonal() #4.24
It's a rough code, but I'll put the answer I came up with for reference.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return (self.radius ** 2) * 3.14
def perimeter(self):
return self.radius * 2 * 3.14
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def area(self):
area = self.height * self.width
print(f'{area:.2f}')
def diagonal(self):
line = pow(self.height, 2) + pow(self.width, 2)
line = line ** (1/2)
print(f'{line:.2f}')
Correct answer if the execution result is as follows!
3.14
6.28
28.26
18.84
30.00
7.81
9.00
4.24
Recommended Posts