Condensed python/ruby code for problem 4