Python3版本號比較代碼實現

1、版本號比較的困難

不能直接以字符串形式進行比較:對於1.3和1.4直接以字符串進行比較是能夠正確得出1.4比1.3大;但若是是1.3和1.14還直接進字符串比較那就是1.3比1.14大那就不對了。函數

不能直用用數值類型進行比較:若是版本號是1和2那能夠自接以整型進行比較,若是是1.3和1.4能夠直接以浮點型進行比較;但若是是1.3.1和1.4.1這種形式,那整型和浮點型都不能用了。spa

 

2、版本號比較實現思路

最關鍵的點就是每次取一節版本號、轉換成整型進行比較;好比1.2.3和1.2.14,先比較1,再比較2,最後再比較3得14。code

 

3、實現

3.1 實現效果

 

3.2 實現代碼

compare_version----遞歸實現版本比較blog

pick_up_latest_version----調用compare_version,打印最終的版本比較結果遞歸

# version1----第一個要比較的版本字符串
# version2----第二個要比較的版本字符串
# split_flag----版本分隔符,默認爲".",可自定義
# 返回值----相等返回0,version1比version2大返回1,version2比version1大返回2
# 接受的版本字符形式----空/x/x.y/x.y./x.y.z;兩個參數可爲前邊列出的形式的任一種
def compare_version(version1=None,version2=None,split_flag="."):
    # 若是存在有爲空的狀況則進入
    if (version1 is None) or (version1 == "") or (version2 is None) or (version2 == ""):
        # version1爲空且version2不爲空,則返回version2大
        if ((version1 is None) or (version1 == "")) and (version2 is not None) and (version2 != ""):
            return 2
        # version2爲空且version1不爲空,則返回version1大
        if ((version2 is None) or (version2 == "")) and (version1 is not None) and (version1 != ""):
            return 1

    # 若是版本字符串相等,那麼直接返回相等,這句會且只會在第一次比較時纔可能進入
    # version1和version2都爲空時也會進入這裏
    if version1 == version2:
        return 0

    # 對版本字符串從左向右查找".",第一個"."以前的字符串即爲這次要比較的版本
    # 如1.3.5中的1
    try:
        current_section_version1 = version1[:version1.index(split_flag)]
    except:
        current_section_version1 = version1
    try:
        current_section_version2 = version2[:version2.index(split_flag)]
    except:
        current_section_version2 = version2
    # 對本次要比較的版本字符轉成整型進行比較
    if int(current_section_version1) > int(current_section_version2):
        return 1
    elif int(current_section_version1) < int(current_section_version2):
        return 2

    # 若是本次傳來版本字符串中已沒有版本號分隔符,那說明本次比較的版本號已經是最後一位版本號,下次比較值賦空
    # 如本次傳來的是5,那下次要比較的只能賦空
    try:
        other_section_version1 = version1[version1.index(split_flag)+1:]
    except:
        other_section_version1 = ""
    try:
        other_section_version2 = version2[version2.index(split_flag) + 1:]
    except:
        other_section_version2 = ""

    # 遞歸調用比較
    return compare_version(other_section_version1,other_section_version2)

# 此函數調用compare_version(),打印比較結果
def pick_up_latest_version(version1,version2):
    flag = compare_version(version1,version2)
    if flag == 0:
        print(f"version1 = {version1}, version2 = {version2}, the two version is equal")
    elif flag == 1:
        print(f"version1 = {version1}, version2 = {version2}, the latest version is version1 {version1}")
    elif flag == 2:
        print(f"version1 = {version1}, version2 = {version2}, the latest version is version2 {version2}")
相關文章
相關標籤/搜索