Tuesday, May 22, 2012

Roman strings

Get numeric number out of a roman string, linear time Given: mapping I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 Input/Output: II = 2, III = 3, IV = 4 VI, VII, VIII IX = 9 XL = 40, XLIX = 49

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

def roman(string):
  prev = 0
  totalsum = 0

  for c in string:
    if mapping[c] <= prev:
      totalsum = totalsum + mapping[c]
    else:
      totalsum = totalsum - prev
      totalsum = totalsum + mapping[c] - prev

    prev = mapping[c]

  print(totalsum)

roman("XCIX")

No comments:

Post a Comment