-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp089.py
87 lines (76 loc) · 1.63 KB
/
p089.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
ones_dict = ['',
'I',
'II',
'III',
'IV',
'V',
'VI',
'VII',
'VIII',
'IX']
tens_dict = ['',
'X',
'XX',
'XXX',
'XL',
'L',
'LX',
'LXX',
'LXXX',
'XC']
hunds_dict = ['',
'C',
'CC',
'CCC',
'CD',
'D',
'DC',
'DCC',
'DCCC',
'CM']
thous_dict = ['',
'M',
'MM',
'MMM',
'MMMM',
'MMMMM']
def roman_writer(num):
ones = num % 10
tens = num % 100 // 10
hunds = num % 1000 // 100
thous = num % 10000 // 1000
s = []
if thous > 0:
s.append(thous_dict[thous])
if hunds > 0:
s.append(hunds_dict[hunds])
if tens > 0:
s.append(tens_dict[tens])
if ones > 0:
s.append(ones_dict[ones])
return ''.join(s)
def roman_reader(num):
table = {'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000}
s = 0
idx = 0
while idx < len(num):
if idx != len(num)-1 and table[num[idx]] < table[num[idx+1]]:
s += table[num[idx+1]]-table[num[idx]]
idx += 2
else:
s += table[num[idx]]
idx += 1
return s
with open('inputs/p089.txt','r') as infile:
savings = 0
for line in infile:
r = line.strip()
min_r = roman_writer(roman_reader(r))
savings += len(r)-len(min_r)
print(savings)