Skip to content

Instantly share code, notes, and snippets.

@sergmelikyan
Last active November 28, 2017 19:24
Show Gist options
  • Save sergmelikyan/32e67725e882b16a018d0978cd43d967 to your computer and use it in GitHub Desktop.
Save sergmelikyan/32e67725e882b16a018d0978cd43d967 to your computer and use it in GitHub Desktop.
import unittest
class Solution(object):
def compareVersion(self, version1, version2):
"""
Compares two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1,
otherwise return 0.
Assumes 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. Assumes only 4 levels of the revisions.
:type version1: str
:type version2: str
:rtype: int
"""
matchedVersion1 = version1.split(".")
matchedVersion2 = version2.split(".")
for i in range(0, 3):
elemVersion1 = matchedVersion1[i:i+1] or 0
elemVersion2 = matchedVersion2[i:i+1] or 0
if elemVersion1 < elemVersion2:
return -1
if elemVersion1 > elemVersion2:
return 1
return 0
class TestSolution(unittest.TestCase):
solution = Solution()
def test_single_less(self):
self.assertEqual(self.solution.compareVersion("1", "2"), -1)
def test_single_more(self):
self.assertEqual(self.solution.compareVersion("2", "1"), 1)
def test_single_equal(self):
self.assertEqual(self.solution.compareVersion("1", "1"), 0)
def test_double_less(self):
self.assertEqual(self.solution.compareVersion("1.2", "2.3"), -1)
def test_double_more(self):
self.assertEqual(self.solution.compareVersion("2.2", "1.4"), 1)
def test_double_equal(self):
self.assertEqual(self.solution.compareVersion("1.1", "1.1"), 0)
def test_double_and_triple_version(self):
self.assertEqual(self.solution.compareVersion("1.1", "1.1.2"), -1)
def test_quadruple_and_double_version(self):
self.assertEqual(self.solution.compareVersion("1.0.0.0", "1.0.0"), 0)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment