DSA assignment ported from PHP to Python (Django)