I am a beginner, and so I have decided to program a Roman Numeral to Arabic integer converter. I came up with all of the code on my own. There are differing opinions about what constitutes 'proper' Roman Numerals. For example, 'IIII' is odd but known to exist in ancient writings, and 'VIIV' is a silly but parsable way to write '8'. And so my program will treat any valid string as acceptable and attempt to parse it.
It works and I would welcome any comments or considerations, especially with regards to the following:
- general best practice,
- whether the input verification can be made cleaner,
- if there is a nicer way than using a dictionary to match the characters and values,
- efficiency of the part which calculates the totals, and
- if I should add comments to the code.
import re bad = 1 while bad == 1: roman = input('Enter a Roman Numeral: ') test = re.findall('[^IVXLCDM]+', roman) lengthtracker = 0 for item in test: length = len(item) lengthtracker = lengthtracker + length if length != 0: print('Roman Numerals may contain only the characters I, V, X, L, C, D, M') break else: continue if lengthtracker == 0: bad = 0 print('Roman Numeral verified!') ref = dict() ref['I'] = 1 ref['V'] = 5 ref['X'] = 10 ref['L'] = 50 ref['C'] = 100 ref['D'] = 500 ref['M'] = 1000 n = len(roman) m = 0 total = 0 negtotal = 0 tenttotal = 0 while m < n-1: if ref[roman[m]] == ref[roman[m+1]]: tenttotal = tenttotal + ref[roman[m]] elif ref[roman[m]] > ref[roman[m+1]]: total = total + tenttotal + ref[roman[m]] tenttotal = 0 else: negtotal = negtotal + tenttotal + ref[roman[m]] tenttotal = 0 print(total, negtotal, tenttotal) m = m + 1 total = total + tenttotal + ref[roman[m]] - negtotal print('It equals:', total)