Last active
June 17, 2022 23:10
-
-
Save gawen/0432112a628fbb4c7c08 to your computer and use it in GitHub Desktop.
Compare versions in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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