mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
34 lines
991 B
Python
34 lines
991 B
Python
"""Convert to and from Roman numerals
|
|
|
|
This program is part of "Dive Into Python 3", a free Python book for
|
|
experienced programmers. Visit http://diveintopython3.org/ for the
|
|
latest version.
|
|
"""
|
|
class OutOfRangeError(ValueError): pass
|
|
|
|
roman_numeral_map = (('M', 1000),
|
|
('CM', 900),
|
|
('D', 500),
|
|
('CD', 400),
|
|
('C', 100),
|
|
('XC', 90),
|
|
('L', 50),
|
|
('XL', 40),
|
|
('X', 10),
|
|
('IX', 9),
|
|
('V', 5),
|
|
('IV', 4),
|
|
('I', 1))
|
|
|
|
def to_roman(n):
|
|
"""convert integer to Roman numeral"""
|
|
# if n > 3999:
|
|
# raise OutOfRangeError("number out of range (must be less than 3999)")
|
|
|
|
result = ""
|
|
for numeral, integer in roman_numeral_map:
|
|
while n >= integer:
|
|
result += numeral
|
|
n -= integer
|
|
return result
|