Created
May 28, 2014 14:17
-
-
Save GuillermoPena/08f67b252adc3a5e314d to your computer and use it in GitHub Desktop.
CheckIO - Home Challenge 8 : 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
# CheckIO - Home Challenge 8 : Roman Numerals | |
# http://checkio.org | |
# Roman numerals come from the ancient Roman numbering system. | |
# They are based on specific letters of the alphabet which are combined | |
# to signify the sum (or, in some cases, the difference) of their values. | |
# The Roman numeral system is decimal based but not directly positional and does not include a zero. | |
# Roman numerals are based on combinations of these seven symbols: | |
# Symbol Value | |
# I 1 (unus) | |
# V 5 (quinque) | |
# X 10 (decem) | |
# L 50 (quinquaginta) | |
# C 100 (centum) | |
# D 500 (quingenti) | |
# M 1,000 (mille) | |
# For this task, you should return a roman numeral using the specified integer value ranging from 1 to 3999. | |
# Input: A number as an integer. | |
# Output: The Roman numeral as a string. | |
# Precondition: 0 < number < 4000 | |
ROMANS=['M','D','C','L','X','V','I'] | |
VALUES=[1000,500,100,50,10,5,1] | |
def checkio(number): | |
roman='' | |
# Zero case | |
if (number==0): return '' | |
# Special cases | |
if (str(number)[0]=='9' or str(number)[0]=='4'): | |
if (number>899 and number<1000): roman+='CM'+checkio(number%100) | |
if (number>399 and number<500): roman+='CD'+checkio(number%100) | |
if (number>89 and number<100): roman+='XC'+checkio(number%10) | |
if (number>39 and number<50): roman+='XL'+checkio(number%10) | |
if (number==9): roman+='IX'+checkio(0) | |
if (number==4): roman+='IV'+checkio(0) | |
return roman | |
# Other cases | |
i=0 | |
while i<len(VALUES): | |
value=VALUES[i] | |
if number>=value: | |
for x in range(0,number//value): | |
number-=value | |
roman+=ROMANS[i] + checkio(number) | |
return roman | |
i+=1 | |
if __name__ == '__main__': | |
#These "asserts" using only for self-checking and not necessary for auto-testing | |
assert checkio(6) == 'VI', '6' | |
assert checkio(76) == 'LXXVI', '76' | |
assert checkio(499) == 'CDXCIX', '499' | |
assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment