⇤ ← Revisão 1e 2006-05-30 15:06:40
2423
Comentário:
|
← Revisão 2e 2008-09-26 14:07:19 ⇥
2431
converted to 1.6 markup
|
Deleções são marcadas assim. | Adições são marcadas assim. |
Linha 72: | Linha 72: |
* [http://en.wikipedia.org/wiki/Roman_numerals Números romanos pela Wikipedia] * [http://www.python.org/dev/peps/pep-0313 PEP-313: Adding Roman Numeral Literals to Python] * [http://diveintopython.org/roman_divein.html Implementação com regex de números romanos no Dive Into Python] * [http://zoony23.cafe24.com/mycgi/Roman2/Roman_Conv.html Conversão on-line em Python+CGI] |
* [[http://en.wikipedia.org/wiki/Roman_numerals|Números romanos pela Wikipedia]] * [[http://www.python.org/dev/peps/pep-0313|PEP-313: Adding Roman Numeral Literals to Python]] * [[http://diveintopython.org/roman_divein.html|Implementação com regex de números romanos no Dive Into Python]] * [[http://zoony23.cafe24.com/mycgi/Roman2/Roman_Conv.html|Conversão on-line em Python+CGI]] |
Receita: Conversão de Números Romanos
Os exemplos abaixo se baseiam no capítulo 3.24: Roman Numerals do livro Python Cookbook e que foi rejeitada a proposta para ser uma biblioteca padrão do Python.
O sistema de cifras romanas é escrito com determinadas letras, que representam os números.
Algumas regras:
- As letras são sempre maiúsculas.
- Zero não é representado.
Para transformar um número inteiro em romano:
1 def int_to_roman(input):
2 if not isinstance(input, type(1)):
3 raise TypeError, "expected integer, got %s" % type(input)
4 if not 0 < input < 4000:
5 raise ValueError, "Argument must be between 1 and 3999"
6 ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
7 nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
8 result = []
9
10 for i in range(len(ints)):
11 count = int(input / ints[i])
12 result.append(nums[i] * count)
13 input -= ints[i] * count
14 return ''.join(result)
Para transformar um número romano em inteiro:
1 def roman_to_int(input):
2 if not isinstance(input, type("")):
3 raise TypeError, "expected string, got %s" % type(input)
4 input = input.upper( )
5 nums = {'M':1000,
6 'D':500,
7 'C':100,
8 'L':50,
9 'X':10,
10 'V':5,
11 'I':1}
12 sum = 0
13 for i in range(len(input)):
14 try:
15 value = nums[input[i]]
16 if i+1 < len(input) and nums[input[i+1]] > value:
17 sum -= value
18 else: sum += value
19 except KeyError:
20 raise ValueError, 'input is not a valid Roman numeral: %s' % input
21
22 if int_to_roman(sum) == input: return sum
23 else:
24 raise ValueError, 'input is not a valid Roman numeral: %s' % input
Mais informações: