Version number comparison
<p>Python must have a more elegant solution to this ... maybe one of you can help:</p>

<p>I want to write a <code>cmp</code>-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections. </p>

<p>Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1. </p>

<p>Desired function outputs are</p>

<p><code>mycmp('1.0', '1') == 0</code><br/>
<code>mycmp('1.0.0', '1') == 0</code><br/>
<code>mycmp('1', '1.0.0.1') == -1</code><br/>
<code>mycmp('12.10', '11.0.0.0.0') == 1</code><br/>
...</p>

<p>And here is my implementation, open for improvement:</p>

<pre><code>def mycmp(version1, version2):
    parts1 = [int(x) for x in version1.split('.')]
    parts2 = [int(x) for x in version2.split('.')]

    # fill up the shorter version with zeros ...
    lendiff = len(parts1) - len(parts2)
    if lendiff &gt; 0:
        parts2.extend([0] * lendiff)
    elif lendiff &lt; 0:
        parts1.extend([0] * (-lendiff))

    for i, p in enumerate(parts1):
        ret = cmp(p, parts2[i])
        if ret: return ret
    return 0
</code></pre>

<p>I'm using Python 2.4.5 btw. (installed at my working place ...).</p>

<p>Here's a small 'test suite' you can use</p>

<pre><code>assert mycmp('1', '2') == -1
assert mycmp('2', '1') == 1
assert mycmp('1', '1') == 0
assert mycmp('1.0', '1') == 0
assert mycmp('1', '1.000') == 0
assert mycmp('12.01', '12.1') == 0
assert mycmp('13.0.1', '13.00.02') == -1
assert mycmp('1.1.1.1', '1.1.1.1') == 0
assert mycmp('1.1.1.2', '1.1.1.1') == 1
assert mycmp('1.1.3', '1.1.3.000') == 0
assert mycmp('3.1.1.0', '3.1.2.10') == -1
assert mycmp('1.1', '1.10') == -1
</code></pre>
