Created
January 17, 2012 00:36
-
-
Save yngwie74/1623819 to your computer and use it in GitHub Desktop.
Implementación "literaria" de la kata "Roman Numerals". La versión sin refactorizar en gist.github.com/1623830
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
""" | |
Implementación de la kata "Roman Numerals" (http://bit.ly/92cEtq). | |
Esta es una implementación "literal" de las reglas de la numeración romana. | |
Fue escrita con el propósito específico de *NO* usar un diccionario en la | |
conversión. | |
Esta versión fue refactorizada para mostrar de forma independiente las | |
partes que componen el algorítmo (responsabilidades). | |
""" | |
from itertools import count, izip | |
_SIMBOLS = ('IVX', 'XLC', 'CDM', 'MMM') | |
def _digitsOf(number): | |
while number > 0: | |
number, r = divmod(number, 10) | |
yield r | |
def _numeralFor(digit, numerals): | |
(one, five, ten) = numerals | |
if digit <= 3: | |
return one * digit | |
elif digit <= 5: | |
return one * (5 - digit) + five | |
elif digit < 9: | |
return five + one * (digit - 5) | |
return one + ten | |
def romanOf(number): | |
result = [_numeralFor(d, p) for d, p in izip(_digitsOf(number), _SIMBOLS)] | |
return ''.join(result[::-1]) | |
if __name__ == '__main__': | |
print romanOf(1999), '-> MCMXCIX' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment