# Compare Version Numbers in Python

Suppose we have to compare two version numbers version1 and version2. If the version1 > version2 then return 1; otherwise when version1 < version2 return -1; otherwise return 0. We can assume that the version strings are non-empty and contain only digits and the dot (.) characters. The dot character does not represent a decimal point and is used to separate number sequences. So for example, 2.5 is not "two and a half" or "halfway to version three", it is the fifth second-level revision of the second first-level revision.

We can assume the default revision number for each level of a version number to be 0. For example, the version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.

So if the input is like version1 = “1.0.1” and version2 = “1”, then it will return +1.

To solve this, we will follow these steps −

• version1_arr = an array of numbers separated by dot for version1

• version2_arr = an array of numbers separated by dot for version2

• for i in range 0 to max of size of version1_arr and size of version2_arr −

• v1 := version1_arr[i] if i < size of version1_arr, otherwise 0

• v2 := version2_arr[i] if i < size of version2_arr, otherwise 0

• if v1 > v2, then return 1, otherwise when v1 < v2, return -1

• return 0

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution:
def compareVersion(self, version1, version2):
versions1 = [int(v) for v in version1.split(".")]
versions2 = [int(v) for v in version2.split(".")]
for i in range(max(len(versions1),len(versions2))):
v1 = versions1[i] if i < len(versions1) else 0
v2 = versions2[i] if i < len(versions2) else 0
if v1 > v2:
return 1
elif v1 <v2:
return -1
return 0
ob1 = Solution()
print(ob1.compareVersion("1.0.1","1.0"))

## Input

"1.0.1"
"1.0"

## Output

1

Updated on: 02-May-2020

2K+ Views 