dimanche 31 mai 2020

Python - Convert a roman numeral to an integer

I've tried the following Python 3 code for Roman to Integer. Which is working fine at a glance. But there are certain problem happened when I input 'X', 'V' or related to 'X' and 'V' value. For example: Input: 'V' not working but Input: 'IV' showing correct value.

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 message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

I've set the condition which is, if the input roman number is equal or less than "MMMCMXCIX", it will print the roman number; else it will print "Try again". But the problem is when I input 'X', 'V' or related to 'X' and 'V' value the output is showing "Try again".

Please help me to understand where I went wrong. Thank you.

Aucun commentaire:

Enregistrer un commentaire