Skip to content

32. A Comparable Version Class

Difficulty: Medium · Topic: OOP & classes

Write a class Version("1.10.2") for dotted version numbers that behaves like a value:

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

(Version('1.10.0') > Version('1.9.9'), Version('2.0') >= Version('2'), Version('0.9') < Version('0.10'))

Expected: (True, True, True)

Hints

Hint 1Turn the text into a tuple of ints, then drop trailing zeros: tuples already compare part by part.
Hint 2@functools.total_ordering fills in the other comparisons from __eq__ and __lt__.
Hint 3Defining __eq__ sets __hash__ to None: define __hash__ on the same normalised tuple. Return NotImplemented for other types.

Learn the concepts

More Python problems

All Python problems