[Tutor] Roman to digital (pseudocode)
János Juhász
janos.juhasz at VELUX.com
Wed Mar 14 09:17:09 CET 2007
Hi All,
> - A dictionary will help you look up values, but not rules. It does
> not retain its order and order is essential. Instead, create a tuple
> of the roman numerals in ascending order (roman). Create a paired
> tuple with the base 10 value (baseten).
> Now get an element from the string you want to test -- use the index
> value in roman to test the rules -- you will know what is higher,
> lower, and the same
> Then look for things like the following:
> - does the following element have a lower index in roman? if yes, you
> know the value (match indexes from the tuples) -- step forward
> - what if the follower is the same? then check the one after, if it is
> the same (and the following digit is lower) then you have a value. --
> step over the last matching digit
> - if the following value is higher, it must be by only one unit, if so
> you have a value, but also a new rule: the following digit must be
> lower than the last digit of the pair.
> and so on.
> not pseudocode I know, and I am certain there are better ways to do
> this, but maybe something here helps.
#############################
roman_codec = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
original = raw_input('Enter a roman number:')
roman = original.upper()
roman = list(roman) # I would like to use pop instead roman = roman[1:]
roman.reverse() # pop picks from the end, so prepare for it
decimal = [roman_codec[ch] for ch in roman] # turn the chars into decimal
result = 0
while len(decimal):
act = decimal.pop()
if len(decimal) and act < max(decimal): act = -act # if there is a
char with higher score it is minus :)
result += act
print original, '=', result
############################
Python is nearly pseudocode.
This is the reason we like it so much.
Best regards,
Janos Juhasz
More information about the Tutor
mailing list