Roman Numerals | Euler 89
This problem focuses on generating optimum Roman Numeral representation. The python code is provided and text file contains the input text. These are the rules associated with Roman Numbers
getMin() function returns the minimized roman numeral and getNum() function returns the value of the roman numeral in international format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
f = open("p089_roman.txt","r") | |
nums = f.read().strip().split("\n") | |
f.close() | |
romanStd = {"I" :1,"V": 5,"X": 10,"L": 50,"C": 100,"D": 500,"M": 1000} | |
def getNum(string): | |
val = 0 | |
global romanStd | |
x = 0 | |
while(x<len(string)): | |
if(x<len(string)-1 and (romanStd[string[x]] < romanStd[string[x+1]])): | |
val += -romanStd[string[x]] + romanStd[string[x+1]] | |
x+=2 | |
else: | |
val += romanStd[string[x]] | |
x+=1 | |
return val | |
def getMin(string): | |
val = getNum(string) | |
ans ="" | |
#making the thousands of the number (value above thousand) | |
while(val>=1000): | |
val -= 1000 | |
ans += "M" | |
if(val - getNum("CM") >= 0): | |
val = val - getNum("CM") | |
ans += "CM" | |
#500 | |
while(val>=500): | |
val -= 500 | |
ans += "D" | |
if(val - getNum("CD") >= 0): | |
val = val - getNum("CD") | |
ans += "CD" | |
#100 | |
while(val >= 100): | |
val -= 100 | |
ans += "C" | |
if(val - getNum("XC") >= 0): | |
val = val - getNum("XC") | |
ans += "CX" | |
#50 | |
while(val >= 50): | |
val -= 50 | |
ans += "L" | |
if(val - getNum("XL") >= 0): | |
val = val - getNum("XL") | |
ans += "XL" | |
#10 | |
while(val >= 10): | |
val -= 10 | |
ans += "X" | |
if(val - getNum("IX") >= 0): | |
val = val - getNum("IX") | |
ans += "IX" | |
#5 | |
while(val >= 5): | |
val -= 5 | |
ans += "V" | |
if(val - getNum("IV") >= 0): | |
val = val - getNum("IV") | |
ans += "IV" | |
ans += "I"*val | |
return ans | |
saving = 0 | |
for x in nums: | |
if(len(x) - len(getMin(x)) <0): | |
print x | |
saving += len(x) - len(getMin(x)) | |
print saving | |
Comments
Post a Comment