Semantic Version Sorting

medium
Unit 14 · Parsing & Decorators0/3 to milestone

Package managers sort versions like 1.10.0 above 1.9.0, which string sorting gets wrong, and know that a pre-release such as 2.0.0-rc.1 comes before 2.0.0.

Implement parse_version(v) returning a tuple you can compare, compare(a, b) returning -1, 0 or 1, and sort_versions(versions). Follow the core SemVer rules:

  • MAJOR.MINOR.PATCH, compared numerically. An optional leading v is allowed.
  • An optional pre-release after -, with dot-separated identifiers. A version with a pre-release is lower than the same version without one.
  • Pre-release identifiers are compared one by one: numeric identifiers numerically, alphanumeric ones as strings, numeric identifiers sort below alphanumeric ones, and a shorter list of identifiers is lower if all its identifiers match the start of the longer one.
  • Build metadata after + is ignored.

Raise ValueError for malformed versions.

#parsing#sorting#devtools2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Semantic Version Sorting · TechGradify