Login

How to compare two versions?

Author:
RafRaf
Posted:
November 23, 2013
Language:
Python
Version:
1.6
Tags:
comparison
Score:
0 (after 0 ratings)

ver_cmp('1.6.2', '1.6')

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def ver_cmp(v1, v2):
    lst = map(lambda x, y: ((0 if not x else x), (0 if not y else y)),
              v1.split('.'), v2.split('.'))

    for num1, num2 in lst:
        if num1 != num2:
            if num1 > num2:
                return (1, 'greater')
            else:
                return (2, 'less')
    return (0, 'equal')

    # Example:
    #
    # >>> print ver_cmp('1.6.2', '1.6')
    # >>> (1, 'greater')

More like this

Comments

syntaxsugar (on November 25, 2013):
<p>Why not use distutils module?</p> <pre>from distutils.version import StrictVersion >>> StrictVersion('1.6.2') > StrictVersion('1.6') True </pre>

#

Please login first before commenting.