I looked through a couple of "Learn Python" websites before finding this Reddit post where the person was looking for exactly what I wanted. I dislike the websites where your code has to match the key EXACTLY and I would rather have the key just check my result against expected. I am working through the "missions" on Check.Io and am really enjoying it. I thought I would document my journey through learning Python on here mostly as a reference for me, but maybe it will be fun for other people as well.
One of the first tasks is to write a program to convert numeric values to Roman numerals. For my solution, I decided to create a dictionary that holds the numeric to numeral translation (1 = I, 5 = V, etc) and then set up a function that takes each place (one, ten, hundred, thousand) and converts it to Roman Numerals.
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
#Roman Numerals | |
#Converts any number from 1 to 3999 into Roman Numerals | |
#Dictionary to translate numbers into Roman Numerals | |
def RN_RomNum(): | |
RomNum = dict() | |
RowNum[0] = '' | |
RomNum[1] = 'I' | |
RomNum[5] = 'V' | |
RomNum[10] = 'X' | |
RomNum[50] = 'L' | |
RomNum[100] = 'C' | |
RomNum[500] = 'D' | |
RomNum[1000] = 'M' | |
return RomNum | |
#Function that creates the Roman Numeral "Pattern" | |
#Uses the Dictionary. | |
def translate(x,low,med,high): | |
RomNum = RN_RomNum() | |
if x == '0': | |
return '' | |
elif x == '1': | |
return RomNum[low] | |
elif x == '2': | |
return RomNum[low]*2 | |
elif x == '3': | |
return RomNum[low]*3 | |
elif x == '4': | |
return RomNum[low]+RomNum[med] | |
elif x == '5': | |
return RomNum[med] | |
elif x == '6': | |
return RomNum[med]+RomNum[low] | |
elif x == '7': | |
return RomNum[med]+RomNum[low]*2 | |
elif x == '8': | |
return RomNum[med]+RomNum[low]*3 | |
elif x == '9': | |
return RomNum[low]+RomNum[high] | |
#Main Function | |
#Converts numeric into a 4 character string and runs each of those "places" through | |
#the translation above. | |
def convert(x): | |
if x >= 4000 or x < 1: | |
return 'Error: Please choose a number greater than 0 and less than 4000' | |
strX = str(x) #Converts to a string | |
while len(strX) < 4: #Pads number with zeroes to end with a 4 character string | |
strX = '0' + strX | |
one = translate(strX[3],1,5,10) | |
ten = translate(strX[2],10,50,100) | |
hund = translate(strX[1],100,500,1000) | |
thou = translate(strX[0],1000,0,0) | |
result = thou+hund+ten+one | |
return result |