String index out of bounds ( Python : Dict ) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: String index out of bounds ( Python : Dict ) (/thread-27880.html) |
String index out of bounds ( Python : Dict ) - kommu - Jun-25-2020 Hello All, I am trying to convert Roman number to Integer (III-->3) and to do that I need to compare characters one by one in a dictionary. How do I not get this error? If this was a string I can do where S[i]=s[i+1], Tried to do same in the dictionary but it is throwing me an error. def prit(num,count): i=0 while(i<len(num)): if(len(num)==1): count = count + dict1[num[0]] if(len(num)==0): print(count) exit() else: if(dict1[num[i]]>=dict1[num[i+1]]): count = count + dict1[num[i]] i=i+1 else: count = dict1[num[i+1]]-dict1[num[i]]+count i=i+2 return count num="LVIII" count=0 dict1 = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } count=prit(num,count) print(count) RE: String index out of bounds ( Python : Dict ) - menator01 - Jun-25-2020 Please use proper tags when posting. Here is a working example #! /usr/bin/env python3 roman = { 'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 } def convert(rn): converted = [] for val in rn: if val in roman.keys(): converted.append(roman[val]) return sum(converted) print(convert('XVI'))
RE: String index out of bounds ( Python : Dict ) - menator01 - Jun-25-2020 Gonna go ahead and add one to convert to roman numerals. This one took a while to figure out. Using the same dict as above. def to_roman(num): keys = [] values = [] for key in roman.keys(): keys.append(key) for value in roman.values(): values.append(value) keys.reverse() values.reverse() rom = '' i = 0 while num > 0: for _ in range(num // values[i]): rom += keys[i] num -= values[i] i += 1 return rom print(to_roman(326))
|