2

I am trying to compare android version numbers in my code. If any version is less than 4.1 I want that version number.

Should I use comparison on strings directly as below?

Examples:

"4.0.3" < "4.1" # should return.
"5.0" < "4.1"  # should not return.
Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
Kishan Mehta
  • 2,598
  • 5
  • 39
  • 61
  • You can directly compare this string in Python, It will give you the expected results. – Sunil Lulla Jul 21 '17 at 07:14
  • 8
    **No you should not**. `10.2 < 4.1` returns `True`. String comparisons take place one character at a time. In the example above `'1'` is compared against `'4'` and loses. – Ma0 Jul 21 '17 at 07:14
  • 1
    Look at this topic: https://stackoverflow.com/questions/11887762/compare-version-strings-in-python – CrazyElf Jul 21 '17 at 07:30
  • I think I should use `from distutils.version import LooseVersion` . – Kishan Mehta Jul 21 '17 at 07:45

1 Answers1

0

Try this

def compare_versions_greater_than(v1, v2):
    for i, j in zip(map(int, v1.split(".")), map(int, v2.split("."))):
        if i == j:
            continue
        return i > j
    return len(v1.split(".")) > len(v2.split("."))

a = "2.0.3"
b = "2.1"
print(compare_versions_greater_than(a, b))
print(compare_versions_greater_than(b, a))

Output

False
True
Himaprasoon
  • 2,609
  • 3
  • 25
  • 46