solve problem 3 in python and ruby