Skip to content

Commit 49585e4

Browse files
authored
Merge pull request #1478 from ivan1016017/december07
adding algo
2 parents 4bbc1c2 + 6995184 commit 49585e4

4 files changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def romanToInt(self, s: str) -> int:
6+
7+
roman_to_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
8+
9+
len_s = len(s)
10+
11+
answer = roman_to_dict[s[len_s - 1]]
12+
13+
for i in range(len_s - 1):
14+
15+
if roman_to_dict[s[len_s - 2 - i]] \
16+
< roman_to_dict[s[len_s - 1 - i]]:
17+
answer -= roman_to_dict[s[len_s - 2 - i]]
18+
else:
19+
answer += roman_to_dict[s[len_s - 2 - i]]
20+
21+
return answer
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def intToRoman(self, num: int) -> str:
6+
# Creating Dictionary for Lookup
7+
num_map = {
8+
1: "I",
9+
5: "V", 4: "IV",
10+
10: "X", 9: "IX",
11+
50: "L", 40: "XL",
12+
100: "C", 90: "XC",
13+
500: "D", 400: "CD",
14+
1000: "M", 900: "CM",
15+
}
16+
17+
# Result Variable
18+
r = ''
19+
20+
21+
for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
22+
# If n in list then add the roman value to result variable
23+
while n <= num:
24+
r += num_map[n]
25+
num-=n
26+
return r
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_17_roman_to_integer import Solution
4+
5+
class RomanToIntegerTestCase(unittest.TestCase):
6+
7+
def test_patter_one(self):
8+
solution = Solution()
9+
output = solution.romanToInt(s='VII')
10+
target = 7
11+
self.assertEqual(output, target)
12+
13+
def test_patter_two(self):
14+
solution = Solution()
15+
output = solution.romanToInt(s='IX')
16+
target = 9
17+
self.assertEqual(output, target)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_18_integer_to_roman import Solution
4+
5+
class IntegerToRomanTestCase(unittest.TestCase):
6+
7+
def test_patter_one(self):
8+
solution = Solution()
9+
output = solution.intToRoman(num = 3749)
10+
target = "MMMDCCXLIX"
11+
self.assertEqual(output, target)
12+
13+
def test_patter_two(self):
14+
solution = Solution()
15+
output = solution.intToRoman(num = 58)
16+
target = "LVIII"
17+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)