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,023
  • 2
  • 28
  • 62
Kishan Mehta
  • 2,307
  • 2
  • 34
  • 54
  • 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

2 Answers2

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,419
  • 3
  • 23
  • 44
-2

You can transform the version string to float. And then compare them.

def version2float(version):
    main, *tail = version.split('.')
    temp = ''.join(tail)
    return float('.'.join([main, temp]))
stamaimer
  • 5,797
  • 4
  • 30
  • 52