python求解LeetCode习题Compare Version Numbers

来源:互联网 发布:有哪些类似于知乎 编辑:程序博客网 时间:2024/05/16 11:44

题目

Compare two version numbers version1 and version1.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
翻译:

比较两个给定的版本号的大小,前者大输出1,后者大输出0,无法比较输出0

思路:

题目中说道,版本号都是数值类型的字符串,且包含‘.’,这样可以按照‘.’来进行切割,得到每个版本号的列表,为了比较的方面,对于长度不足的列表进行补充0的操作,无实际意义,仅仅为了方便

好了,思想很简单,下面是具体实现:

#!usr/bin/env python#encoding:utf-8'''__Author__:沂水寒城功能:Compare Version Numbers '''def compare_version_num(version1, version2):    '''    比较版本号大小    前者大输出1,后者大输出0,无法比较输出0    '''    version_list1=[int(one) for one in version1.split('.')]    version_list2=[int(one) for one in version2.split('.')]    # print version_list1    # print version_list2    len1=len(version_list1)    len2=len(version_list2)    big=max(len1, len2)    small=min(len1,len2)    value=big-small    if len1!=big:        version_list1.extend([0]*value)    elif len2!=big:        version_list2.extend([0]*value)    # print version_list1    # print version_list2    i=0    while i<big:        if version_list1[i]>version_list2[i]:            print 1            break        elif version_list1[i]<version_list2[i]:            print -1            break        else:            i+=1            if __name__ == '__main__':    compare_version_num('1.2','1.2.4')    compare_version_num('1.1.3','1.0.4')    compare_version_num('1.2','2.2.4')    compare_version_num('1.2.3.0','1.2.4')

结果如下:

-11-1-1[Finished in 0.3s]




原创粉丝点击