Editor

Fix the Version Comparator

Intermediate · Fix the bug · from How to Package and Publish Your Python Code to PyPI

From the lesson: How to Package and Publish Your Python Code to PyPI

Imagine you've written a fantastic recipe. Right now it only lives in your kitchen notebook. To share it with the world, you'd need to format it nicely, package it into a cookbook, and get it onto bookstore shelves.

Read the lesson

The code below compares two version strings (like '1.2.3') to determine which is newer. There's a bug causing wrong results. Fix it so compare_versions correctly returns 'newer', 'older', or 'equal'.

def compare_versions(v1, v2):
'''Compare v1 to v2. Returns newer, older, or equal.'''
parts1 = v1.split('.')
parts2 = v2.split('.')
for i in range(max(len(parts1), len(parts2))):
p1 = parts1[i] if i < len(parts1) else '0'
p2 = parts2[i] if i < len(parts2) else '0'
if p1 > p2:
return 'newer'
elif p1 < p2:
return 'older'
return 'equal'
print(compare_versions('1.0.0', '1.0.0'))
print(compare_versions('2.0.0', '1.0.0'))
print(compare_versions('1.10.0', '1.9.0'))
print(compare_versions('1.0.0', '1.0.1'))

More PyPI Packaging exercises

All Python exercises · 50 practice problems · Modules & Packaging quiz