[Original] python compares two versions, python version
#-*-Coding: UTF-8-*-_ author _ = 'ypp' import redef versionCompare (v1 = "1.1.1", v2 = "1.2"): v1_check = re. match ("\ d + (\. \ d +) {0, 2} ", v1) v2_check = re. match ("\ d + (\. \ d +) {0, 2} ", v2) if v1_check is None or v2_check is None or v1_check.group ()! = V1 or v2_check.group ()! = V2: return "the version number format is incorrect. The correct format is x. x. x, which can only contain 3 "vswitchlist = v1.split (". ") v2_list = v2.split (". ") v1_len = len (v1_list) v2_len = len (v2_list) if v1_len> v2_len: for I in range (v1_len-v2_len): v2_list.append (" 0 ") elif v2_len> v1_len: for I in range (v2_len-v1_len): v1_list.append ("0") else: pass for I in range (len (v1_list): if int (v1_list [I])> int (v2_list [I]): return "v1 large" if int (v1_list [I]) <int (v2_list [I]): return "v2" return "equal" # Test Case print (versionCompare (v1 = "", v2 = "") print (versionCompare (v1 = "1.0.a ", v2 = "d.0.1") print (versionCompare (v1 = "1.0.1", v2 = "1.0.1") print (versionCompare (v1 = "1.0.2 ", v2 = "1.0.1") print (versionCompare (v1 = "1.0.1", v2 = "1.0.2") print (versionCompare (v1 = "1.0.11 ", v2 = "1.0.2 "))
Design Philosophy:
1. Use regular expressions to determine whether the version number format is correct
2. Separate the string with "." into an array.
3. Compare the length of the array. Fill the short array with "0" to an array of equal length.
4. Traverse array elements one by one and compare the size
Test cases:
1. the version number is empty.
2. the version number contains non-numbers.
3. the version number length is inconsistent.
4. version numbers are separated by vertices and compared by bit.