[Original] python compares two versions, python version

Source: Internet
Author: User

[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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.