python - Roman to Numeral calculator with "for i in X" -
i tried build calculator convert roman numeral can tell me how can choose 2 characters words in high priority?
** roman string
#roman numeral calculator def romantodecimal(roman): decimalvalue=0 in roman: if == "cm": decimalvalue += 900 if == "iv": decimalvalue += 4 if == "ix": decimalvalue += 9 if == "xl": decimalvalue += 40 if == "xc": decimalvalue += 90 if == "cd": decimalvalue += 400 elif in roman: if == "i": decimalvalue += 1 if == "v": decimalvalue += 5 if == "x": decimalvalue += 10 if == "l": decimalvalue += 50 if == "c": decimalvalue += 100 if == "d": decimalvalue += 500 if == "m": decimalvalue += 1000 return decimalvalue
and i'm new here please try answer me patience
while there more efficient ways this, follows style of own code easier follow.
the main change replace for
loop while
loop , manual counter. makes possible skip ahead 2 steps when encounter 1 of our double-chars. next extract characters , inspect them — first looking 2 chars ahead, next looking individually. if find match @ 2 chars long step forward 2 (past them) , restart loop:
def romantodecimal(roman): decimalvalue=0 = 0 # position in string while < len(roman): # test 2 char first if < len(roman)-1: # make sure we're not on last letter # current + next letters s = roman[i:i+2] add = false if s == "cm": add = 900 elif s == "iv": add = 4 elif s == "ix": add = 9 elif s == "xl": add = 40 elif s == "xc": add = 90 elif s == "cd": add = 400 if add: # we've found match += 2 # step 2 decimalvalue += add # add value continue # next loop # if here 2 character match failed # single char match s = roman[i] if s == "i": decimalvalue += 1 elif s == "v": decimalvalue += 5 elif s == "x": decimalvalue += 10 elif s == "l": decimalvalue += 50 elif s == "c": decimalvalue += 100 elif s == "d": decimalvalue += 500 elif s == "m": decimalvalue += 1000 += 1 return decimalvalue romantodecimal('xixix') 28
it should noted above not really valid roman numeral string (28 correctly represented xxviii), that's not problem!
let me know if code unclear anywhere , add more comments.
Comments
Post a Comment