-
Notifications
You must be signed in to change notification settings - Fork 0
/
romans_inc.py
161 lines (139 loc) · 2.47 KB
/
romans_inc.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python2
"""
Conversion of arabic numbers to roman numerals.
This implementation uses a rather brutish approach. By defining an increment
function we can create all roman numerals inductively.
"""
import doctest
successors = { 'I': 'V',
'V': 'X',
'X': 'L',
'L': 'C',
'C': 'D',
'D': 'M',
'M': None,
}
predecessors = { 'I': None,
'V': 'I',
'X': 'V',
'L': 'X',
'C': 'L',
'D': 'C',
'M': 'D',
}
def succ(numeral):
return successors[numeral]
def pred(numeral):
return predecessors[numeral]
def inc(r):
"""
>>> inc('I')
'II'
>>> inc('III')
'IV'
>>> inc('IV')
'V'
>>> inc('V')
'VI'
>>> inc('VI')
'VII'
>>> inc('VII')
'VIII'
>>> inc('VIII')
'IX'
>>> inc('X')
'XI'
>>> inc('XIV')
'XV'
>>> inc('XXXVIII')
'XXXIX'
>>> inc('XXXIX')
'XL'
>>> inc('LXXXIX')
'XC'
>>> r = 'I'
>>> s = set()
>>> while True:
... s.add(r)
... try:
... r = inc(r)
... except Exception:
... break
>>> len(s)
3999
"""
r += 'I'
while True:
if r.endswith('IIII') \
or r.endswith('XXXX') \
or r.endswith('CCCC'):
r = r[:-3] + succ(r[-1])
elif r.endswith('MMMM'):
raise Exception()
elif r.endswith('IVI') \
or r.endswith('IXI') \
or r.endswith('XLX') \
or r.endswith('XCX') \
or r.endswith('CDC') \
or r.endswith('CMC'):
r = r[:-3] + r[-2]
elif r.endswith('VIV') \
or r.endswith('LXL') \
or r.endswith('DCD'):
r = r[:-3] + r[-2] + succ(r[-1])
else:
break
return r
def dec(r):
"""
>>> dec('II')
'I'
>>> dec('IV')
'III'
>>> dec('V')
'IV'
>>> dec('VI')
'V'
>>> dec('IX')
'VIII'
>>> dec('X')
'IX'
>>> r = 'I'
>>> for n in range(1,3999):
... assert(r == dec(inc(r)))
... r = inc(r)
"""
while True:
if r.endswith('I'):
r = r[:-1]
break
elif r.endswith('IV') \
or r.endswith('XL') \
or r.endswith('CD'):
r = r[:-2] + 4 * r[-2]
if r.endswith('IX') \
or r.endswith('XC') \
or r.endswith('CM'):
r = r[:-2] + pred(r[-1]) + 4 * r[-2]
elif r.endswith('X') \
or r.endswith('C') \
or r.endswith('M'):
r = r[:-1] + pred(pred(r[-1])) + r[-1] + pred(pred(r[-1]))
elif r.endswith('V') \
or r.endswith('L') \
or r.endswith('D'):
r = r[:-1] + pred(r[-1]) + r[-1] + pred(r[-1])
return r
def romanize(n):
"""
>>> romanize(23)
'XXIII'
>>> romanize(42)
'XLII'
"""
r = 'I'
for i in range(n-1):
r = inc(r)
return r
if __name__ == "__main__":
doctest.testmod()