associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Você não tem permissão para executar esta ação.

Excluir mensagem

NumerosRomanos

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)

   1 >>> int_to_roman(112)
   2 'CXII'
   3 >>> 

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

   1 >>> roman_to_int('LIII')
   2 53
   3 >>> 

Mais informações:

LeonardoGregianin