Python code for comparing version numbers


  • 0
    A
        def compareVersion(version1, version2):
            """
            :type version1: str
            :type version2: str
            :rtype: int
            """
            
            vers1 = version1.split('.')
            vers2 = version2.split('.')
            
            l1 = len(vers1)
            l2 = len(vers2)
            
            l = min(l1,l2)
            
            for idx in xrange(l):
                if int(vers1[idx])>int(vers2[idx]):
                    return 1
                if int(vers1[idx])<int(vers2[idx]):
                    return -1
            
            if l1>l2:
                ver1 = [int(vers1[idx])==0 for idx in xrange(l2,l1)]
                if all(ver1):
                    return 0
                else:
                    return 1
            elif l1<l2:
                ver2 = [int(vers2[idx])==0 for idx in xrange(l1,l2)]
                if all(ver2):
                    return 0
                else:
                    return -1
            else:
                return 0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.