[Tutor] The whole Roman to Dec and vice versa issue

John Fouhy john at fouhy.net
Sun Mar 11 23:35:12 CET 2007


On 12/03/07, Jaggo <jaggojaggo at yahoo.com> wrote:
> Hey,
> I'm a rather new programmer, but it seems to me the digital to roman should
> be coded:
> While Digital_Input > 0:
> If Digital_Input > 1000 then: Roman = + M, Digital_Input = - 1000
> elif Digital_Input > 900 then: Roman = + C, Digital_Input = - 900
> ...
> Now if someone could please clarify [or forward me to clarifications of-]
> separation of data from logics I should be very grateful.

The idea is that our data is the information:
 1000 corresponds to 'M'
 500 corresponds to 'D'
 100 corresponds to 'C'
 etc..

We can represent that in python using a dictionary:

decToRomanData = { 1000:'M', 500:'D', 100:'C', 50:'L', 10:'X', 5:'V', 1:'I' }

Now we need to write some code that will take an integer and use our
data to convert to a Roman numeral.  One way we could do that is:

def decToRoman(dec):
        roman = ''
        while dec > 0:
                next = max(i for i in decToRomanData if dec >= i)
                roman += decToRomanData[next]
                dec -= next
        return roman

Now, if we suddenly remember that the romans used 'Q' to represent
250, we can just edit our dictionary, and the rest of the code will
remain the same.

[note that this code will not produce strings like 'IV' for 4.  OTOH,
as I recall, the Romans didn't do that consistently either..]

-- 
John.


More information about the Tutor mailing list