User:Inductiveload/Integer to Roman numerals converter
Appearance
Python
[edit]This function takes a (positive) integer and returns a string holding the Roman numeral of that number.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def roman_numerals(x):
#Returns an upper-case Roman Numeral string representation of a decimal integer, n
numeral_chars = (('M', 1000),('CM', 900), ('D', 500), ('CD', 400),
('C', 100), ('XC', 90), ('L', 50), ('XL', 40),
('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1))
#RN character groups for each value up to 1000 (past this requires overbar)
roman_num = []#initialise the list of characters groups
for chr, value in numeral_chars:#for each group
(remainder,x) = divmod(x, value)#work out how many of that group are needed, and remove from n
roman_num.append(chr*remainder)#add the right number of groups to the list
result = ''#empty string to populate
return result.join(roman_num)#add each character group to the string and return