Skip to content

Commit 8a428ae

Browse files
committed
added
1 parent 344c518 commit 8a428ae

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

int_to_roman.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Learn Python together
2+
""" Write a function that converts integer to roman numerical"""
3+
4+
# Solution
5+
def int_to_roman(num: int) -> str:
6+
# create the list with tuples representing the romans and their values
7+
roman_map = [
8+
('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100),
9+
('XC', 90), ('L', 50), ('XL', 40), ('X', 10),
10+
('IX', 9), ('V', 5), ('IV', 4), ('I', 1)
11+
]
12+
if num <= 0:
13+
return "Roman numerals don't represent 0 or negative numbers"
14+
# epmty result
15+
result = ''
16+
# using for loop for iterate over the roman_map list:
17+
for roman, value in roman_map:
18+
# while loop runs until the value of the current roman is greater than the num
19+
while value <= num:
20+
result += roman # For each iteration of the while loop, the roman is added to the result
21+
num -= value # and the value is subtracted from num
22+
return result
23+
24+
# check
25+
print(int_to_roman(1994)) # output -> MCMXCIV
26+
print(int_to_roman(-609)) # output -> Roman numerals don't represent 0 or negative numbers
27+
print(int_to_roman(0)) # output -> Roman numerals don't represent 0 or negative numbers
28+
print(int_to_roman(609)) # output -> DCIX

roman_to_int.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,30 @@ def romanToInt(s):
1919
# use for loop for chcecking characters in range of lenths a string - s
2020
for i in range(len(s)):
2121
#check if chararter in s(string) is > 0 and is second charecter greater then previous character
22+
# if yes, subtract 2 times the value of the previous character and add to result
2223
if i > 0 and roman_dict[s[i]] > roman_dict[s[i - 1]]:
23-
# if yes, subtract 2 times the value of the previous character and add to result
2424
result += roman_dict[s[i]] - 2 * roman_dict[s[i - 1]]
2525
else:
2626
# if second character less then previous character add it to result
2727
result += roman_dict[s[i]]
2828
return result
2929
# check
3030
print(romanToInt('MCMXCIV')) # output -> 1994
31-
print(romanToInt('DCIX')) # output -> 609
31+
print(romanToInt('DCIX')) # output -> 609
32+
33+
# Solution 2
34+
def romanToInt2(s: str) -> int:
35+
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
36+
result = 0
37+
prev_value = 0
38+
for c in s[::-1]:
39+
curr_value = roman_dict[c]
40+
if curr_value >= prev_value:
41+
result += curr_value
42+
else:
43+
result -= curr_value
44+
prev_value = curr_value
45+
return result
46+
47+
print(romanToInt2('MCMXCIV')) # output -> 1994
48+
print(romanToInt2('DCIX')) # output -> 609

0 commit comments

Comments
 (0)