Checkio: Roman numerals

題目:

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 first ten Roman numerals are:

I, II, III, IV, V, VI, VII, VIII, IX, and X.

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)

More additional information about roman numerals can be found on the Wikipedia article.

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.

Example:

checkio(6)=='VI'
checkio(76)=='LXXVI'
checkio(13)=='XIII'
checkio(44)=='XLIV'
checkio(3999)=='MMMCMXCIX'
How it is used: This is an educational task that allows you to explore different numbering systems. Since roman numerals are often used in the typography, it can alternatively be used for text generation. The year of construction on building faces and cornerstones is most often written by Roman numerals. These numerals have many other uses in the modern world and you read about it here... Or maybe you will have a customer from Ancient Rome ;-)

Precondition: 0 < number < 4000

我的代碼如下,儘管比較簡單,我覺得這個代碼算是比較清晰的了。

def checkio(data):
   
    s = ''
    ones = ['X','I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
    tens = ['C', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
    mils = ['M', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
   
    if data / 1000 != 0:
        s = s + 'M'*(data/1000)
        data = data % 1000
    if data / 100 != 0:
        s = s + mils[data/100]
        data = data % 100
    if data / 10 != 0:
        s = s + tens[data/10]
        data = data % 10
    if data / 1 != 0:
        s = s + ones[data/1]
    return s

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'
下面是checkio上面clear裏面最火的答案:

elements = { 1000 : 'M', 900 : 'CM', 500 : 'D', 400 : 'CD', 
             100 : 'C', 90 : 'XC', 50 : 'L', 40: 'XL', 
             10 : 'X', 9 : 'IX', 5 : 'V', 4: 'IV', 1 : 'I' }
              
def checkio(data):
    roman = ''
     
    for n in sorted(elements.keys(), reverse=True):
        while data >= n:
            roman += elements[n]
            data -= n
 
    return roman
看了吧,總是有人思路更清晰些。Come and On!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章