Rubykuby

Romannumerals1

Jan 6th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. NUMERALS = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
  2.  
  3. def previous_is_combo(numeral, index):
  4.     if index - 1 < 0:
  5.         return False
  6.  
  7.     current = NUMERALS[numeral[index]] # Current number extracted from the dictionary
  8.     previous = NUMERALS[numeral[index-1]] # Previous number extracted from the dictionary
  9.  
  10.     if current > previous:
  11.         return True
  12.     else:
  13.         return False
  14.  
  15.  
  16. def next_is_combo(numeral, index):
  17.     current = NUMERALS[numeral[index]] # Current number extracted from the dictionary
  18.     try:
  19.         next = NUMERALS[numeral[index+1]] # Next number extracted from the dictionary
  20.     except IndexError:
  21.         return False
  22.  
  23.     if current < next:
  24.         return True
  25.     else:
  26.         return False
  27.  
  28. def compare(numeral, index):
  29.     if next_is_combo(numeral, index):
  30.         return NUMERALS[numeral[index+1]] - NUMERALS[numeral[index]]
  31.     elif previous_is_combo(numeral, index):
  32.         return 0
  33.     else:
  34.         return NUMERALS[numeral[index]]
  35.  
  36. def numeral_to_decimal(numeral):
  37.     decimal = 0
  38.  
  39.     for letter in range(len(numeral)):
  40.         decimal += compare(numeral, letter)
  41.  
  42.     return decimal
  43.  
  44. def main():
  45.     print(numeral_to_decimal("MCMLIV"))
  46.     print()
  47.     print(numeral_to_decimal("MMVIII"))
  48.     print()
  49.     print(numeral_to_decimal("MCMXC"))
  50.     print()
  51.     print(numeral_to_decimal("MCDIV"))
  52.  
  53. if __name__ == "__main__":
  54.     main()
Advertisement
Add Comment
Please, Sign In to add comment