Skip to content

Instantly share code, notes, and snippets.

@ballgoesvroomvroom
Last active May 23, 2022 11:21
Show Gist options
  • Save ballgoesvroomvroom/3835039fbaf1dd1cc8633a31c0a974a9 to your computer and use it in GitHub Desktop.
Save ballgoesvroomvroom/3835039fbaf1dd1cc8633a31c0a974a9 to your computer and use it in GitHub Desktop.
integers to roman numerals
ordered = [
1, 5, 10, 50, 100, 500, 1000
]
mapping = {
1: "I",
5: "V",
10: "X",
50: "L",
100: "C",
500: "D",
1000: "M",
4: "IV",
9: "IX",
40: "XL",
90: "XC",
400: "CD",
900: "CM"
}
def toRoman(n):
## only takes in numbers with 1 deciding character; followed by leading zeroes
r = ""
if n in mapping:
return mapping[n]
else:
index = 0
for x in ordered:
if n < x:
break
index += 1
index -= 1
multiplierFactor = 0
while True:
multiplierFactor += 1
if ordered[index] *multiplierFactor > n:
multiplierFactor -= 1
break
foundN = mapping[ordered[index]] *(multiplierFactor)
r += foundN
if n - ordered[index] *multiplierFactor > 0:
nn = n - ordered[index] *multiplierFactor
a = toRoman(nn)
r += a
return r
def intToRoman(num: int):
d = ""
index = -1
for i in range(len(str(num)) -1, -1, -1):
index += 1
value = int(str(num)[i]) *(10 **index)
if value == 0:
continue
roman = toRoman(value)
d = "{}{}".format(roman, d)
return d
if __name__ == "__main__":
while True:
inp = 0
while True:
prompt = input("Integer to convert to roman numerals: ")
if prompt.isdigit():
inp = int(prompt)
break
else:
print("Invalid input; try again.\n")
print("Roman numeral: {}\n".format(intToRoman(inp)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment