Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement __lt__ and __le__ for Version Objects

Create a Version class that compares semantic version strings using < and <=.

Python practice16 minMagic Methods & Operator OverloadingIntermediateLast updated April 11, 2026

Problem statement

Implement a Version class that accepts a version string such as 'MAJOR.MINOR.PATCH' (parts are integers). Implement the rich comparison methods __lt__ and __le__ to compare versions lexicographically by their integer components. The implementation should handle version strings with differing lengths by treating missing components as zero (for example, '1.2' == '1.2.0'). Provide a readable __repr__ for easier debugging and test output.

Task

Implement __lt__ and __le__ so Version instances correctly compare semantic version numbers like '1.2.3'.

Examples

Compare two versions

Input

Version('1.2.3') < Version('1.3.0')

Output

True

Compare major (1==1), then minor (2<3) so the first is less.

Input format

Each test is a single Python expression that constructs Version objects and uses < or <=.

Output format

Return a boolean; the harness compares its string form 'True' or 'False' to the expected output.

Constraints

Version parts are non-negative integers separated by dots. Compare by integer values, padding shorter versions with zeros for comparison.

Samples

Sample 1

Input

Version('2.0.0') <= Version('2.0')

Output

True

'2.0' is treated as '2.0.0' so they are equal and <= returns True.