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

Kent Johnson kent37 at tds.net
Mon Mar 12 00:20:58 CET 2007

```John Fouhy wrote:
> 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' }

A list would probably work better here because the order is significant
and random lookup is not.
>
> 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

Remember this thread started as a homework problem...we shouldn't give
solutions until the OP has one already. Then we can all get clever and
show how we would have done it :-)
>
> 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..]

It seems to me that isn't so different from deciding to use 'Q' for 250.
Maybe you can change the dictionary for this one too.

Kent
```