Eneko Alonso

un Navarro en California

Projects

¿Eres español y vives fuera de España? ¿Estás pensando en salir una temporada a trabajar o estudiar en el extranjero? Si es así, no dejes de visitar Spaniards.es, la Comunidad de Españoles en el Mundo
spaniards.es

Recent comments

17:10 America/Los_Angeles


Comparing versions in Python

A couple of days ago I had to implementDue to a bug we had with internationalization. a class in Delphi to compare software version numbers. I wanted to do it right, so I created a class for comparing versions that we could use everywhere in the system. Nothing hard, but still it required a bunch of lines of code to do it.

You may be wondering why all this, why not compare just the version strings? Well, because it doesn't work :P For example, if we compare the strings '1.0.100.5' and '1.0.110.5' the result will be the first one is smaller, which is right:

>>> print '1.0.100.5' < '1.0.110.5' True

But if we compare '1.0.100.5' against '1.0.11.5', the result is wrong, since it will say the first one is still smaller:

>>> print '1.0.100.5' < '1.0.11.5' True

Obviously, that is not true, since the first version is greater or newer than the second one.

So I wanted to know how simple would be to do this in Python. I was picturing on my mind using regular expressions to extract all 4 version numbers (major, minor, release and build) and then comparing them as lists, which would return the good result.

So I implemented it and it was just as simple as I expected. Well, not exactly as simple as I expected since regular expressions return strings. I solved this using a combination of map and lambda functions:

>>> import re >>> verA = '1.0.100.5' >>> verB = '1.0.11.5' >>> verA = map(lambda x: int(x), re.findall('\d+', verA)) >>> verB = map(lambda x: int(x), re.findall('\d+', verB)) >>> print verA < verB False >>>

Update May 10th 2008

Sometimes regular expressions are a little bit 'too much'. I mean, sometimes it's just better to use string functions which may work even faster:

>>> verA = map(lambda x:int(x), verA.split('.'))

As you can see, we still need the lambda function to convert the string parts to integers. Probably there is also a way to make this easier :)

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.