I am trying to generate dictionary values of roman numerals, but I am really stuck in designing my for loop. In my problem, you have an input called values. For each distinct letter in the input, it corresponds to a roman numeral. In the example below, A=1,B=5,C=10,D=50,E=100,F=500,G=1000 etc. Thus,the letters of the input are just like the roman numerals, I,V,X,L,C,D. I want to create a function where you input a string of any length and each distinct letter corresponds to a roman numeral which is put into a dictionary
values='ABCDEFGHI'
dict={}
for i,letter in enumerate(values):
if i%2==1:
dict[letter]=5*10**(i)
else:
dict[letter]=1*10**i
print(dict)
I have come up with a pattern, but don't know how to implement that into a for loop: This link shows a table with the pattern I found
I am having problems because at each certain iteration you need to subtract more and more from the power and I dunno what that looks like.
CodePudding user response:
I actually came up with this solution which works as well haha! Thank you mjsqu for your alternative solution too here is what i did
def dictcreator(value):
dict={}
n=0
for i,letter in enumerate(reversed(value)):
if i%2==1:
dict[letter]=5*10**(i-n)
else:
dict[letter]=1*10**(i-n)
n=n 1
return dict
CodePudding user response:
Thanks to the commenter, I think there's no need to use subtraction in the power, just note that the power increases more slowly, at half the rate of i, so this works:
romans={}
for i,letter in enumerate(values):
power=int(0.5*(i))
print(f"{i=}")
print(f"{power=}")
if i%2==1:
romans[letter]=5*10**(power)
else:
romans[letter]=1*10**(power)
>>> romans
{'A': 1, 'B': 5, 'C': 10, 'D': 50, 'E': 100, 'F': 500, 'G': 1000, 'H': 5000, 'I': 10000}