We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Modelling Data with Dataclasses step 2 of 28
Sort Version Numbers with a Dataclass
Your tool lists releases such as 1.2.0, 1.10.0 and 0.9.9, oldest first.
Sorting the strings gets the order wrong. "1.10.0" < "1.2.0" is True,
because strings compare one character at a time. Sort records of three
integers instead.
solve([[1, 0, 10], [1, 0, 2], [0, 9, 9], [1, 0, 2]])
# ["0.9.9", "1.0.2", "1.0.2", "1.0.10"]
What to write
Fill in the Version dataclass:
- Give it three
intfields in this order:major,minor,patch. - Decorate it with
@dataclass(slots=True, frozen=True, order=True). Leave the other options at their defaults, so all three fields take part in comparisons.
order=True compares major first, then minor, then patch, so 1.99.99
sorts before 2.0.0. frozen=True stops code from changing a version after
you make it. slots=True stores the fields in fixed slots instead of a
dictionary on each object, so you cannot add other attributes to a
Version. The article Save Memory with slots=True covers it later in this
track.
Then fill in solve(versions):
- Each inner list holds three non-negative integers, in the order major, minor, patch.
- Build a
Versionfrom each list and sort the versions from lowest to highest. - Return each version as a string in the form
"major.minor.patch", such as"1.0.10", with no spaces and no zero-padding. - Keep duplicates, and leave the input list unchanged.
Your code must pass mypy --strict.
Edge cases
- An empty list returns an empty list.
- You do not need to check for malformed input.
Sort the Version records first, then turn them into strings. If you turn
them into strings first and sort those, "1.0.10" sorts before "1.0.2".
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
Python reference solution
Sign in to track your attempts toward unlocking the reference solution.