Problem 4 in Python and Ruby