Login

How to compare two versions?

Author:
RafRaf
Posted:
November 23, 2013
Language:
Python
Version:
1.6
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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

syntaxsugar (on November 25, 2013):

Why not use distutils module?

from distutils.version import StrictVersion
>>> StrictVersion('1.6.2') > StrictVersion('1.6')
True

#

Please login first before commenting.