I've tried the following Python 3 code that transform from Roman to Integer.
The code is working fine at a glance. But there are certain problem happened when I input an integer number or string (ex: 1, 2 or any integer number, string) it shows some code error. I want when I input any thing except roman number (within 1 to 3999) it should return "Try again".
Here is my code:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
i = 0
num = 0
while i < len(s):
if i+1<len(s) and s[i:i+2] in roman:
num+=roman[s[i:i+2]]
i+=2
else:
#print(i)
num+=roman[s[i]]
i+=1
return num
ob1 = Solution()
message = str(input("Please enter your roman number: "))
if (ob1.romanToInt(message)) <= 3999:
print (ob1.romanToInt(message))
else:
print ("Try again")
Try this:
message = str(input("Please enter your roman number: "))
try:
n = ob1.romanToInt(message)
if n > 3999: raise Exception()
print(n)
except Exception:
print("Try again")