Note that there are some explanatory texts on larger screens.

plurals
  1. POVersion number comparison in Python
    primarykey
    data
    text
    <p>I want to write a <code>cmp</code>-like function which compares two version numbers and returns <code>-1</code>, <code>0</code>, or <code>1</code> based on their compared valuses.</p> <ul> <li>Return <code>-1</code> if version A is older than version B</li> <li>Return <code>0</code> if version A and B are equivalent</li> <li>Return <code>1</code> if version A is newer than version B</li> </ul> <p>Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1. </p> <p>Desired function outputs are</p> <pre><code>mycmp('1.0', '1') == 0 mycmp('1.0.0', '1') == 0 mycmp('1', '1.0.0.1') == -1 mycmp('12.10', '11.0.0.0.0') == 1 ... </code></pre> <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>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload