Python: problem 52

Ugliest code ever