HackerRank Python (Basic) certification
String Representation of Objects
This question tests one dunder method, __str__. The logic is trivial. What fails people is a single wrong character in the output sentence.
What the question asks
Write two classes:
Car, created with a maximum speed (an integer) and a speed unit (a string such askm/hormph). When a Car is converted to a string, it should readCar with the maximum speed of <speed> <unit>.Boat, created with only a maximum speed. Boat speeds are always in knots, so a Boat converts toBoat with the maximum speed of <speed> knots.
The stub reads lines like car 151 km/h or boat 77, builds the object, and writes it with "%s" % vehicle, which calls your __str__.
Function to write
class Car:
def __init__(self, max_speed, speed_unit): ...
def __str__(self): ...
class Boat:
def __init__(self, max_speed): ...
def __str__(self): ...Only the two classes are yours. Input reading and output are in HackerRank’s code.
Solution
class Car:
def __init__(self, max_speed, speed_unit):
self.max_speed = max_speed
self.speed_unit = speed_unit
def __str__(self):
return f"Car with the maximum speed of {self.max_speed} {self.speed_unit}"
class Boat:
def __init__(self, max_speed):
self.max_speed = max_speed
def __str__(self):
return f"Boat with the maximum speed of {self.max_speed} knots"How it works
- The constructors just store what they are given.
print(obj),str(obj), f-strings and"%s" % objall callobj.__str__()to get the text. Without it, Python prints something like<__main__.Car object at 0x10...>.- The f-string drops the stored values into the fixed sentence. The speed is an
int, and the f-string converts it for you.
Every public solution I checked uses exactly these two sentences, with no full stop at the end.
Mistakes that fail the hidden tests
- Any change in the sentence. “Maximum” with a capital M, “max speed”, a full stop at the end, “knot” instead of “knots”, or two spaces somewhere. The checker compares the text exactly. Copy the sentence carefully from the question on test day.
- Printing inside
__str__.__str__must return the string. If it prints and returns nothing, Python raises “__str__ returned non-string (type NoneType)”. - Writing the unit into the Car string. The unit changes from test to test (
km/h,mphand so on). Only the Boat has a fixed unit. - Using
__new__to return a string. Some public answers do this. It passes because the stub only prints the result, but the “object” is then just a string and not a Car. Use__str__, which is what the question is testing.
Defining __repr__ instead of __str__ also passes, because Python falls back to __repr__ when __str__ is missing. __str__ is the right method for human-readable text, so use that.
Try it on sample data
Input in the stub’s format:
2
car 151 km/h
boat 77
Output from my run with a copy of the stub’s loop:
Car with the maximum speed of 151 km/h
Boat with the maximum speed of 77 knots