Integer to Roman
So, I had this simple assignment recently to code up a Django application to convert an integer between 1 and 3999 to its corresponding roman numeral. The first thing that hit me was to write up the request response part as simple as possible – but it was simple as it is! What could be simpler? Ok.. that is settled.
Ok what next? The logic – I was pretty sure the moment I thought about the problem that the best answers cannot be more than 4 to 5 lines. When I was learning to program in Haskell and Erlang about a year ago, I learnt how differently a problem can be approached. But Haskell has inbuilt functions that simplifies working with recursions and loops. With Python, some of those functions need to be rewritten.
Ok, coming back to our problem in question, I decided to use some of the basic functions in Python. So, here is the core logic I came up with:
# Symbol map for conversion from Integer to Roman numeral symbol_map = (("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)) def int2roman(n): # Calculating roman numeral value by using divmod roman_value =  for symbol, value in symbol_map: (m, n) = divmod(n, value) roman_value.append(symbol * m) return "".join(roman_value)
I think it is a neat idea to loop it and then perform simple manipulations on the symbol_map to obtain the desired result. You can fork the source at Github for the full Django application. Feel free to discuss the source in the comments section below.