Compare piece by piece
Decide which of two version numbers like 1.10 and 1.9 is newer. About 10 minutes.
Text order isn't number order
Your phone says an update from version 1.9 to 1.10 is available. Is 1.10 newer? Compared as text, no: the character 1 comes before 9. Compared as numbers, 10 is bigger than 9, so yes.
So split each version at the dots and turn every part into a real number. A part like "010" is just the number 10: leading zeros don't matter.
As text, "1.2" looks bigger, because the character 2 beats 1. That's the trap. Split on the dots and compare numbers.
The first difference decides
Compare the first parts, then the second parts, and so on. The first pair that differs decides which version is newer.
If one version runs out of parts, treat its missing parts as 0. So 1.0 and 1.0.0 are equal, and 2.5.10 is newer than 2.5.9 because the first two parts match and 10 beats 9.
a = [int(p) for p in v1.split(".")]
b = [int(p) for p in v2.split(".")]
for i in range(max(len(a), len(b))):
x = a[i] if i < len(a) else 0
y = b[i] if i < len(b) else 0
if x != y:
return 1 if x > y else -1
return 0Which is newer, 2.5.10 or 2.5.9?
- A2.5.10
- B2.5.9
- CThey're equal
Show the answer
2.5.10. The first two parts match; 10 > 9 decides.
Compare versions
You get two version strings made of whole numbers separated by dots, like "1.10.2". Compare them part by part as numbers, treating missing parts as 0. Return 1 if the first is bigger, −1 if it is smaller, and 0 if they are equal.
v1 = "1.2", v2 = "1.10" → -1
1 ≤ lengths ≤ 500 · every part fits in an int · parts may have leading zeros