Skip to content

Instantly share code, notes, and snippets.

@gawen
Last active June 17, 2022 23:10
Show Gist options
  • Save gawen/0432112a628fbb4c7c08 to your computer and use it in GitHub Desktop.
Save gawen/0432112a628fbb4c7c08 to your computer and use it in GitHub Desktop.
Compare versions in Python
def cmp_version(va, vb):
# Split over '.' and convert members into int
va = map(int, va.split("."))
vb = map(int, vb.split("."))
# Get max length of versions
l = max(len(va), len(vb))
# Make the version the same length by appending 0
va = va + [0] * (l - len(va))
vb = vb + [0] * (l - len(vb))
assert len(va) == len(vb)
# Use Python tuple comparaison operator
if va < vb:
return -1
elif va > vb:
return 1
return 0
assert cmp_version('1', '2') == -1
assert cmp_version('2', '1') == 1
assert cmp_version('1', '1') == 0
assert cmp_version('1.0', '1') == 0
assert cmp_version('1', '1.000') == 0
assert cmp_version('12.01', '12.1') == 0
assert cmp_version('13.0.1', '13.00.02') == -1
assert cmp_version('1.1.1.1', '1.1.1.1') == 0
assert cmp_version('1.1.1.2', '1.1.1.1') == 1
assert cmp_version('1.1.3', '1.1.3.000') == 0
assert cmp_version('3.1.1.0', '3.1.2.10') == -1
assert cmp_version('1.1', '1.10') == -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment