0
1

More than 3 years have passed since last update.

スパルタキャンプPython編 2019 Day2 課題

Posted at

動画上では課題の答えがわからなかったので自分なりに解いてみました。
スパルタキャンプのライブ動画で学習している方の参考になればと思い書きました。

課題

オブジェクト指向プログラミングの初級問題です。
オブジェクト指向を使った良いコードの書き方というよりも、正しい文法で記述できるかを目的としています。

次のコードが正しくなるようなCircleクラスを実装してください。
areaは面積、perimeterは周囲長(円周の長さ)という意味です。

circle.py
#半径1の円
circle1 = Circle(radius=1)
print(circle1.area()) #3.14
print(circle1.perimeter()) #6.28

#半径3の円
circle3 = Circle(radius=3)
print(circle3.area()) #28.26 ←恐らく動画での28.27は誤り
print(circle3.perimeter()) # 18.84 ←恐らく動画での18.85は誤り


#次のコードが正しく動作するようなRectangleクラスを実装してください
#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

答え

雑なコードですが、自分が導き出した答えを参考までに載せておきます

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}')

実行結果が以下のようになれば正解!

3.14
6.28
28.26
18.84
30.00
7.81
9.00
4.24
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1