Skip to content

Instantly share code, notes, and snippets.

@yelluw
Last active April 18, 2017 02:32
Show Gist options
  • Save yelluw/a851f7cf38d2c6446fa9ea41264e414f to your computer and use it in GitHub Desktop.
Save yelluw/a851f7cf38d2c6446fa9ea41264e414f to your computer and use it in GitHub Desktop.
Roman numeral calculator
"""
Roman Numeral calculator
"""
def value(numeral):
"""
numeral = string
Returns base 10 value of roman numeral
if found else returns None
"""
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
return values.get(numeral.upper())
def substract(numerals):
"""
numerals = list of roman numerals (string)
Checks if last numeral in numerals is biggest number
Meaning we need to substract from it
Returns True or False
"""
return value(numerals[0]) < value(numerals[len(numerals) - 1])
def validate(input_numerals):
"""
input_numerals = string
Returns list of numerals or False
"""
try:
numerals = list(input_numerals)
except TypeError:
return False
if all(value(i) for i in numerals):
return numerals
return False
def calculate(numerals):
"""
numerals = list of roman numerals (string)
returns int total value of roman numerals
"""
total = 0
nums = validate(numerals)
if nums:
substraction = substract(nums)
else:
return "Please enter a valid roman numeral"
if substraction:
# take last value in list
# to substract from
total = value(nums.pop())
for n in nums:
total -= value(n)
return total
for n in nums:
total += value(n)
return total
print(calculate("miiv")) # Answer: 1007
print(calculate("iiv")) # Answer: 3
print(calculate("miiv3")) # Error!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment