50 XP

69. Compare version numbers

Intermediate parsing strings

Software versions are written as numbers separated by dots, such as 2.7 or 1.10.3. They are compared part by part, from the left, as whole numbers: the first part that differs decides. So 1.10 is newer than 1.9, because 10 is more than 9, even though the text "1.10" sorts before "1.9".

Write a function compare(v1, v2) that takes two version strings and returns:

  • 1 if v1 is newer than v2,
  • -1 if v1 is older than v2,
  • 0 if they are the same version.

A part that is missing counts as 0, so 2, 2.0 and 2.0.0 are all the same version. Zeros in front of a part don't matter: 1.01 is the same as 1.1.

Example 1

Inputv1 = "1.10", v2 = "1.9"
Output1
Explanation1 equals 1, then 10 is more than 9.

Example 2

Inputv1 = "2.0", v2 = "2"
Output0
ExplanationThe missing part of "2" counts as 0.

Example 3

Inputv1 = "0.9.9", v2 = "1.0"
Output-1
Explanation0 is less than 1: the first part decides.

Constraints

  • v1 and v2 have 1 to 10 parts separated by single dots.
  • Each part is 1 to 4 digits.

Submit also runs 9 more tests you can't see.

Practises String Methods (lesson 5).

Code
def compare(v1, v2):
    """Compare two version numbers.

    v1: str, a version such as "1.10.2"
    v2: str, a version such as "1.9"
    Returns: int, 1 if v1 is newer, -1 if older, 0 if the
        same
    """
    # Write your code here
    pass