Roman numerals

Roman numerals

罗马数字的题目, 注意几个关键的数字即可: (100, 400, 500, 900) -> ('C', 'CD', 'D', 'CM'); (10, 40, 50, 90)->('X', 'XL', 'L', 'XC')

 

 1 def checkio(data):
 2     rel = ''
 3 
 4     thonsand = data / 1000
 5     rel += thonsand * 'M'
 6 
 7     data %= 1000
 8 
 9     table = [['C', 'CD', 'D', 'CM'], ['X', 'XL', 'L', 'XC']]
10     
11     pos = 100
12 
13     for i in range(0, 2):
14         bit = data / pos
15         if bit > 0:
16             if bit < 4:
17                  rel += bit * table[i][0]
18             elif bit == 4:
19                 rel += table[i][1]
20             elif bit == 5:
21                 rel += table[i][2]
22             elif bit == 9:
23                 rel += table[i][3]
24             else:
25                 rel += (table[i][2] + table[i][0] * (bit - 5))
26 
27         data %= pos
28         pos /= 10
29 
30     if data > 0:
31          unit = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
32          rel += unit[data - 1]
33 
34     #replace this for solution
35     return rel

另外还需注意没有个位数的情况, 即第30行所示

观摩JulianNicholls的代码

 1 elements = { 1000 : 'M', 900 : 'CM', 500 : 'D', 400 : 'CD', 
 2              100 : 'C', 90 : 'XC', 50 : 'L', 40: 'XL', 
 3              10 : 'X', 9 : 'IX', 5 : 'V', 4: 'IV', 1 : 'I' }
 4               
 5 def checkio(data):
 6     roman = ''
 7      
 8     for n in sorted(elements.keys(), reverse=True):
 9         while data >= n:
10             roman += elements[n]
11             data -= n
12  
13     return roman

  sorted(elements.keys(), reverse=True), 按key从大到小排列; 思路不错, 比数位对应的值大, 即加上该数位对应的字母, 并减去对应的数值, 直到data为0

posted @ 2014-08-05 10:27  哲人善思  阅读(341)  评论(0编辑  收藏  举报