Sort the versions

Package managers must put versions in order, including pre-releases such as 2.0.0-rc.1. Write the comparison.

What to build

A program that sorts versions from oldest to newest and finds the newest stable one.

Requirements

  • A version is MAJOR.MINOR.PATCH, optionally followed by a dash and a pre-release of dot-separated identifiers, like 1.0.0-rc.1.
  • Compare MAJOR, MINOR and PATCH as numbers. If they are equal, a version with a pre-release is lower than the same version without one.
  • Two pre-releases are compared identifier by identifier: identifiers that are all digits compare as numbers, and are lower than identifiers with letters; identifiers with letters compare as text; if all shared identifiers are equal, the one with fewer identifiers is lower.
  • Print the versions in order from lowest to highest, one per line. Then print latest stable: V with the highest version that has no pre-release, or latest stable: none.

Input

The first line has n (1 to 30). Each of the next n lines is a version. All are valid and different.

Output

n sorted versions, then the latest stable line.

Constraints

1 ≤ n ≤ 30.

Example

Input:

5
1.10.0
1.2.0
1.9.3
2.0.0
1.2.10

Output:

1.2.0
1.2.10
1.9.3
1.10.0
2.0.0
latest stable: 2.0.0

Why it works

Turning each version into a tuple whose parts already compare the right way lets sorted() do the work; marking a release with a larger last element than any pre-release puts it after them, and the stable filter simply drops versions that have a dash.

Examples

Example 1 · Input
5
1.10.0
1.2.0
1.9.3
2.0.0
1.2.10
Expected output
1.2.0
1.2.10
1.9.3
1.10.0
2.0.0
latest stable: 2.0.0
Example 2 · Input
4
2.0.0
2.0.0-rc.1
2.0.0-beta.2
1.9.0
Expected output
1.9.0
2.0.0-beta.2
2.0.0-rc.1
2.0.0
latest stable: 2.0.0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Turn each version into a key: (major, minor, patch, extra) where extra is (1,) for a release and (0, ids) for a pre-release.

Hint 2

In a pre-release, each identifier that is all digits becomes (0, number) and any other becomes (1, text).

Hint 3

Python compares tuples and lists part by part, and a shorter list that is a prefix of a longer one is smaller.

Solution

Show one correct solution (try it yourself first)
def key(version):
    core, _, pre = version.partition("-")
    major, minor, patch = [int(x) for x in core.split(".")]
    if not pre:
        return (major, minor, patch, (1,))
    ids = [(0, int(x), "") if x.isdigit() else (1, 0, x) for x in pre.split(".")]
    return (major, minor, patch, (0, ids))


n = int(input())
versions = [input().strip() for _ in range(n)]
ordered = sorted(versions, key=key)
for version in ordered:
    print(version)
stable = [v for v in ordered if "-" not in v]
print("latest stable: " + (stable[-1] if stable else "none"))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Versions and changelogs →