Expert · Parsing · 256 of 264
Number to Roman numerals
Write a number from 1 to 3999 in Roman numerals, using the subtractive forms (IV, IX, XL, XC, CD, CM).
Input: a whole number. Output: the Roman numeral.
Examples
Input
1994
Output
MCMXCIV
Input
4
Output
IV
Input
3999
Output
MMMCMXCIX
2 more tests check other inputs when you press Check.
Stuck? The idea behind parsing
Turning text into structure: read it piece by piece (tokens: numbers, operators, brackets), then work out what they mean, in order.
A stack keeps what is waiting, such as an operator until both its numbers are known.
tokens = "3 4 + 2 *".split()
stack = []
for t in tokens:
if t in "+*":
b, a = stack.pop(), stack.pop()
stack.append(a + b if t == "+" else a * b)
else:
stack.append(int(t))
print(stack[0]) # 14Watch for: Never run the text with eval(): work it out yourself, so you decide what is allowed.