Editor

Sort Version Numbers

Advanced · Stretch · from Python Lambda Functions: When to Use (and When Not To)

From the lesson: Python Lambda Functions: When to Use (and When Not To)

Imagine you need to leave someone a quick note: "Back in 5 minutes." You wouldn't write a formal letter with a greeting, three paragraphs, and a signature. You'd scribble it on a sticky note and be done.

Read the lesson

Software versions such as "1.10.2" do not sort like text: version 1.10 is newer than 1.9, but as text "1.10" comes first. Write a function sort_versions(versions) that returns a new list from oldest to newest.

sort_versions(["1.10", "1.9", "1.2"])   # ['1.2', '1.9', '1.10']

The rules:

  • Compare the parts between the dots as numbers, from left to right.
  • When one version runs out of parts and everything so far is equal, the shorter one is older: "1.2" comes before "1.2.0".
  • Some versions start with a v ("v2.1"). Ignore it when comparing, but return every version exactly as it was written.
  • Versions that compare equal keep the order they had in the list.
  • Some of the tests are hidden.

    def sort_versions(versions):
    pass
    Solution unlocks after your first Check

    What Check runs

    Your code runs first, then each of these lines, and 4 more that stay hidden. The output must match exactly.

    RunsExpected output
    sort_versions(["1.10", "1.9", "1.2"])['1.2', '1.9', '1.10']
    sort_versions(["2.0.1", "2.0.10", "2.0.9"])['2.0.1', '2.0.9', '2.0.10']

    More Lambda exercises

    All Python exercises · 50 practice problems · Functions quiz