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")
CodePudding user response:
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")
CodePudding user response:
You can try this, check num
in you class and return num
or return Try again
like below:
class Solution(object):
def romanToInt(self, s):
...
...
if 1 <= num <= 3999 :
return ("Try again")
return num
ob1 = Solution()
message = str(input("Please enter your roman number: "))
print(ob1.romanToInt(message))
# if num > 4000 you print 'Try again`
# if num <= 4000 you print num
You can do this with function like below:
class Solution(object):
def chk_num(num):
if 1 <= num <= 3999:
return num
return "Try again"
def romanToInt(self, s):
...
...
return chk_num(num)
ob1 = Solution()
message = str(input("Please enter your roman number: "))
print(ob1.romanToInt(message))