Editor

Fix the Dependency Resolver

Intermediate · Fix the bug · from Python Virtual Environments and pip: A Practical Guide

From the lesson: Python Virtual Environments and pip: A Practical Guide

Imagine you're a carpenter working on two different projects. One needs tiny finishing nails and the other needs heavy-duty bolts. You wouldn't dump all your hardware into one toolbox - you'd have separate toolboxes so the right parts are always ready for the right job.

Read the lesson

The code below simulates a dependency resolver that checks if installed packages satisfy requirements. There are bugs causing incorrect output. Fix them so the resolver correctly identifies which requirements are met and which are not.

def check_dependencies(installed, required):
results = []
for pkg, req_version in sorted(required.items()):
if pkg in installed:
inst_version = installed[pkg]
if inst_version == req_version:
results.append(f'{pkg}: OK ({inst_version})')
else:
results.append(f'{pkg}: MISMATCH (need {req_version}, have {inst_version})')
else:
results.append(f'{pkg}: MISSING')
return results
installed = {
'flask': '3.0.0',
'requests': '2.25.0',
'numpy': '1.24.0',
}
required = {
'flask': '3.0.0',
'requests': '2.31.0',
'pandas': '2.1.4',
}
results = check_dependencies(installed, required)
for r in results:
print(r)
total = len(required)
ok_count = len([r for r in results if 'OK' in r])
print(f'\n{ok_count}/{total} dependencies satisfied')

More Virtual Environment exercises

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