-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroman_first.py
More file actions
executable file
·64 lines (60 loc) · 2.02 KB
/
Copy pathroman_first.py
File metadata and controls
executable file
·64 lines (60 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import re
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))
roman_numeral_pattern = re.compile('''
^ # beginning of string
M{0,4} # thousands - 0 to 3 Ms
(CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs),
# or 500-800 (D, followed by 0 to 3 Cs)
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs),
# or 50-80 (L, followed by 0 to 3 Xs)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is),
# or 5-8 (V, followed by 0 to 3 Is)
$ # end of string
''', re.VERBOSE)
class OutOfRangeError(ValueError):
pass
class NotIntegerError(ValueError):
pass
class InvalidRomanNumeralError(ValueError):
pass
class NotStringError(ValueError):
pass
def to_roman(n):
'''convert integer to Roman numeral'''
if n > 4999 or n <=0:
raise OutOfRangeError('number out of range (must be 1..4999')
if not isinstance(n,int):
raise NotIntegerError('non-integers cannot be converted')
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result
def from_roman(s):
'''convert Roman numeral to integer'''
if not isinstance(s,str):
raise NotStringError('non-strings cannot be converted')
if not s:
raise InvalidRomanNumeralError('Input cannot be blank')
if not roman_numeral_pattern.search(s):
raise InvalidRomanNumeralError('Invalid Roman numeral: {}'.format(s))
result = 0
index = 0
for numeral, integer in roman_numeral_map:
while s[index:index+len(numeral)] == numeral:
result += integer
index+= len(numeral)
return result