Skip to content

Instantly share code, notes, and snippets.

@jehiah jehiah/
Created Apr 10, 2017

What would you like to do?
Semver 2.0.0 compatible version comparison w/o regexes
def compare(a, b):
Compare two version strings.
:return -1, 0, 1
:rtype: int
a = map(_cast_int, a.split('+', 2)[0].split('.'))
b = map(_cast_int, b.split('+', 2)[0].split('.'))
c = _cmp_range(a[:3], b[:3])
if c != 0:
return c
c = _cmp_range(a[3:], b[3:], flip=True)
if c != 0:
return c
if not a[3:]:
return 1
if not b[3:]:
return -1
return c
def _cmp_range(a, b, flip=False):
for i in range(min(len(a), len(b))):
aa = a[i]
bb = b[i]
c = _compare_item(aa, bb, flip)
if c == 0:
return c
return cmp(len(a), len(b))
def _cast_int(a):
return int(a)
return a
def _compare_item(a, b, flip=False):
if isinstance(a, int) and isinstance(b, int):
return cmp(a, b)
elif isinstance(a, int):
return -1 if flip else 1
elif isinstance(b, int):
return 1 if flip else -1
return cmp(a, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.