# Code Kata : Ruby Programming Challenge for Newbies in Python

An interesting contest caught my eye today. There’s a site Ruby Learning by Pune’s Satish Talim (Twitter : @IndianGuru) which organises regular Ruby Programming Challenge for Newbies and it introduced the 13th challenge earlier yesterday : RPCFN: Economics 101 (#13) by Dr. Bruce Scharlau. While neither being a regular rubyist nor being a newbie, I thought it made for a decent exercise and a diversion for a little while, albeit in python. As an added interest I wrote the solutions twice. Once in a very procedural way and once leveraging the functional programming constructs. Here’s the brief problem as stated in the challenge :
The file cia-1996.xml (links back to rublylearning.org) is the data from the CIA World Factbook of 1996 in XML format. It has details about 260 countries across five continents. Your challenge, should you choose to accept it, is to uncover the following details buried within this file:
• What is the population of the country with the most people? Yes, we know itâ€™s China, but just how many people lived there in 1996?
• What are the five countries with the highest inflation rates, and what were those rates in 1996?
• What are the six continents in the file and which countries belong to which continent? Can you also produce them in alphabetical order?
I used python 2.6 with the lxml xml parser for this exercises. Parsing the xml Since the source file is a zip file, one needs to open the zip, and extract the xml out of it. Since I am using python 2.6 and not python 2.7 I couldn’t use the with construct which would’ve not required the explicit zipfile close() statement. This opens the zip file, extracts the xml out of it, concatenates all the lines as a single string and converts the data into a single object referred to as root Note: the itemgetter and itertools imports are used subsequently. Procedural : Find the country with the highest population Procedural : Top 5 countries with highest inflation rates This extracts the inflation, name tuple from each country and creates a list out of it, sorts the list using inflation in a descending order and then prints the first five elements. Procedural : Sorted continents, each associated with all their sorted countries Functional Programming Solutions Incidentally the same problem can also be solved using very functional programming constructs as follows. This shows an interesting contrast of solutions in both the procedural and functional programming ways. The logic used across both the sets is virtually the same thought the constructs are different. Update I further structured the functional programming approach code. This code has no list comprehensions (for loops) at all. The code is as follows : Since the above is likely to be a little too cryptic and confusing, here’s the detailed commented code (only comments and whitespace added)