A Functional-Style Python Solution


  • 0
    B

    This is a functional-style solution to the Compare Version Number problem:

    class Solution:
    # @param version1, a string
    # @param version2, a string
    # @return an integer
    def compareVersion(self, version1, version2):
        def normalize(arr1, arr2):
            arr1, arr2 = map(int, arr1.split('.')), map(int, arr2.split('.'))
            if abs(len(arr1) - len(arr2)) is 0:
                return arr1, arr2
            if len(arr1) > len(arr2):
                while len(arr2) < len(arr1):
                    arr2.append(0)
                return arr1, arr2
            else:
                while len(arr1) < len(arr2):
                    arr1.append(0)
                return arr1, arr2
    
        version1, version2 = normalize(version1, version2)
        for index, num in enumerate(version1):
            if num > version2[index]:
                return 1
            elif num < version2[index]:
                return -1
        return 0
    

    This could actually be faster if you cast to int during the for loop, but I find that to be less clear. Enjoy!


Log in to reply
 

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