Repository navigation
Expand file tree
/
Copy pathrandom_functions.py
More file actions
108 lines (74 loc) · 2.33 KB
/
Copy pathrandom_functions.py
File metadata and controls
108 lines (74 loc) · 2.33 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
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
ROMANS: dict[str, int] = {
"I": 1,
"V": 5,
"X": 10,
"C": 50
}
def roman_to_integer1(romans: str) -> int:
if not romans:
raise ValueError("No Romans Found")
if len(romans) == 1:
return ROMANS[romans]
total: int = 0
i: int = 0
while i < len(romans):
if romans[i] not in ROMANS:
raise KeyError(f"Key {romans[i]} Not Found")
current = ROMANS[romans[i]]
if i + 1 < len(romans):
next = ROMANS[romans[i + 1]]
if current < next:
total += (next - current)
i += 2
continue
total += current
i += 1
return total
def roman_to_integer0(romans: str) -> int:
total = 0
for i in range(len(romans) - 1):
current = ROMANS[romans[i]]
next = ROMANS[romans[i + 1]]
if romans[i] in ROMANS:
if current >= next:
total += current
else:
total -= current
total += ROMANS[romans[-1]]
return total
def roman_to_integer(romans: str) -> int:
if not romans:
raise ValueError("Empty string")
total: int = 0
i: int = 0
while i < len(romans):
if romans[i] not in ROMANS:
raise KeyError("Key not found")
current = ROMANS[romans[i]]
if i + 1 < len(romans):
next = ROMANS[romans[i + 1]]
if current < next:
total += (next - current)
i += 2
continue
total += current
i += 1
return total
try:
print(roman_to_integer("XIX"))
print(roman_to_integer("XIV"))
print(roman_to_integer("XCV"))
print(roman_to_integer("IV"))
print(roman_to_integer("III"))
print(roman_to_integer("X"))
print(roman_to_integer("U"))
except (ValueError, TypeError, KeyError) as e:
print(f"Error: {e}")
def roman_to_integer(romans_str: str) -> int:
if len(romans_str) < 2:
return ROMANS[romans_str]
if len(romans_str) == 2:
return (int(ROMANS[romans_str[0]]) + int(ROMANS[romans_str[1]]))
while len(romans_str) > 2:
for num in romans_str:
if num in ROMANS: