69. Compare version numbers
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:
1ifv1is newer thanv2,-1ifv1is older thanv2,0if 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
v1 = "1.10", v2 = "1.9"1Example 2
v1 = "2.0", v2 = "2"0Example 3
v1 = "0.9.9", v2 = "1.0"-1Constraints
v1andv2have 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).
v1.split(".")gives the parts as strings; turn each into a number withint(), so"10"is more than"9"and"01"equals"1".- Make the two lists the same length by adding zeros to the shorter one:
parts += [0] * (length - len(parts)). - Then compare part by part and return at the first difference; if there is none, return 0. Comparing the strings, or reading
"1.10"as the float 1.1, gives the wrong answer.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.