Program to convert a Roman Numeral into a Decimal Number
Date:- 9th December 2022, Python Lab.
The code for getting the number of digits shows the two ways to get the output, the second function uses the len function and shows how easy it is to do things using functions, and the first one shows a traditional way of approaching the same problem.
def convert(str):
def getNum(st1):
if (st1 == 'I'):
return 1
if (st1 == 'V'):
return 5
if (st1 == 'X'):
return 10
if (st1 == 'L'):
return 50
if (st1 == 'C'):
return 100
if (st1=='D'):
return 500
if (st1=='M'):
return 1000
# if(st1=='-'):
return None
curr = 0
num=0
while (num<len(str)):
str1=getNum(str[num])
if (num+1<len(str)):
str2=getNum(str[num + 1])
if (str1 >= str2):
curr = curr + str1
num = num + 1
else:
curr = curr + str2 - str1
num = num + 2
else:
curr = curr + str1
num = num + 1
return curr
print(convert("MMMM"))
''' To get the number of digits in a decimal number without using any function
like len() '''
def count(num):
coun=0
while(num!=0):
coun+=1
num=num//10
return coun
def count1(num):
return len(str(num))
print(count(56732))
print(count1(56732))
Comments
Post a Comment