HackerRank Python (Basic) certification
Shape Classes with Area Method
This was one of the two questions I got when I took the test. It is a basic classes question: two constructors and two area methods.
What the question asks
Write two classes:
Rectangle, created with the lengths of its two sides. Itsarea()method returns the product of the two sides.Circle, created with its radius. Itsarea()method returns pi times the radius squared. The question asks for an accurate value of pi, and the easy way to get one ismath.pi.
HackerRank’s code reads a number of queries. Each query is a line such as rectangle 2 3 or circle 5. It builds the shape, calls area() and prints the result with two decimal places.
Function to write
class Rectangle:
def __init__(self, length, width): ...
def area(self): ...
class Circle:
def __init__(self, radius): ...
def area(self): ...You only write the two classes. The stub already has import math at the top and handles reading input and printing.
Solution
import math
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2The import math line is already in HackerRank’s stub. I keep it in my copy so the code also runs on its own.
How it works
__init__runs when the stub writesRectangle(2, 3). It stores both sides on the object asself.lengthandself.width.area()reads those stored values and multiplies them.Circlestores the radius the same way.self.radius ** 2squares it, andmath.piis pi to 15 decimal places.- The two classes do not need a common parent class. The stub only calls
area()on whatever shape it built.
Mistakes that fail the hidden tests
- Using 3.14 for pi. For radius 5,
3.14 * 25prints78.50, but the expected answer is78.54. Small radii pass and larger ones fail, which is confusing if you do not know why. - Single underscores in
_init_. It must be__init__with two underscores on each side. With_init_, Python never calls it, andRectangle(2, 3)fails with “takes no arguments”. It is an easy typo to make and a hard one to spot. - Making
areaan attribute instead of a method. The stub callsshape.area()with brackets. If you storeself.area = 6, calling it raises “‘int’ object is not callable”. - Returning a rounded or formatted value. Leave the formatting to the stub. Returning a string breaks its
"%.2f"formatting.
Try it on sample data
Three queries, in the same format the stub reads:
3
rectangle 2 3
circle 1
circle 5
Output from my run of the solution with a copy of the stub’s loop:
6.00
3.14
78.54
Without the formatting, Circle(5).area() returns 78.53981633974483.