在Python中将罗马数字转换为整数

Jak*_*ake 12 python python-3.x

这是现在的用户2486之后的代码.

def romanMap():
    map=(("M",  1000),("CM", 900),("D",  500),("CD", 400),("C",  100),("XC", 90),("L",  50),("XL", 40),("X",  10),("IX", 9),("V",  5),("V", 4),("I",  1))
    return map
firstNum=ns([0])
secondNum=ns([1])
def main():
    ns=str(input("Enter a roman numeral"))
    total=0
    result=0
    while ns:
        firstNum=(romanMap(ns[0]))
         secondNum=(romanMap(ns[1]) 
        if firstNum is len(ns)>1 or secondNum-1:
                        total=total+firstNum
            ns=ns[1:]
        else:
                        total=total+ns[1]-ns[0]
            ns=ns[2:]
      print (total)
main()
Run Code Online (Sandbox Code Playgroud)

我收到此错误的同时ns:UnboundLocalError:在赋值之前引用的局部变量'ns'

Shu*_*ule 22

无需重新发明轮子(除非你想).Python附带一个转换器:

import roman;
n=roman.fromRoman("X"); #n becomes 10
Run Code Online (Sandbox Code Playgroud)

如果您需要数字5000及以上,您需要编写一个新功能,并且可能会使用您自己的字体来表示罗马数字上的线条.(它只适用于某些数字,停在4999是一个非常好的主意.)

要转换为罗马数字,请使用roman.toRoman(myInt).

其他人实际上链接到罗马模块在上面的一条评论中使用的相同源代码,但我不相信他们提到它实际上带有Python.

编辑:请注意,在某些系统(Windows,我认为),您不能只import roman从默认安装中键入.但是,源代码仍可在Windows上运行,并且它包含在此位置的Python 3.4.1源代码下载(可能也是早期版本)中/Python-3.4.1/Doc/tools/roman.py

  • 我不认为它包含在Python中,但是如果你有pip它可以用`pip install roman`安装 (12认同)
  • 我不认为他的教授会接受这一点 (3认同)

r36*_*66y 6

当您添加或减去每个符号的值时,从左到右读取罗马数字.

如果某个值低于以下值,则会减去该值.否则它将被添加.

例如,我们希望将罗马数字MCMLIV转换为阿拉伯数字:

M = 1000 must be added, because the following letter C =100 is lower.
C = 100 must be subtracted because the following letter M =1000 is greater.
M = 1000 must be added, because the following letter L = 50 is lower.
L = 50 must be added, because the following letter I =1 is lower.
I = 1 must be subtracted, because the following letter V = 5 is greater.
V = 5 must be added, because there are no more symbols left.
Run Code Online (Sandbox Code Playgroud)

我们现在可以计算出数字:

1000 - 100 + 1000 + 50 - 1 + 5 = 1954 
Run Code Online (Sandbox Code Playgroud)

参考:http://www.mathinary.com/roman_numerals_from_roman_numerals_to_arabic_numbers.jsp

def from_roman(num):
    roman_numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    result = 0
    for i,c in enumerate(num):
        if (i+1) == len(num) or roman_numerals[c] >= roman_numerals[num[i+1]]:
            result += roman_numerals[c]
        else:
            result -= roman_numerals[c]
    return result
Run Code Online (Sandbox Code Playgroud)


duh*_*ime 6

一个很好的紧凑版本,没有外部库:

def rn_to_int(s):
  d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}
  n = [d[i] for i in s.lower() if i in d]
  return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])


for numeral, expected in [['CLXIV', 164], ['MDCCLXXXIII', 1783], ['xiv', 14]]:
  assert rn_to_int(numeral) == expected
Run Code Online (Sandbox Code Playgroud)


use*_*740 5

考虑这个额外的伪代码和提示(其中一些是有效的Python,有些不是,但有注释).

def numberOfNumeral(n):
    """ Return the number represented by the single numeral """
    # e.g. "v" -> 5, "i" -> 5 (and handle v/V cases, etc.)

# avoid "string" as a variable name
# I chose "ns" for "numerals" (which might be better),
# but I'm also a bit terse .. anyway, name variables for what they represents.
ns = str(input("Enter a roman numeral"))

while ns:
   firstNum = numberOfNumeral(ns[0])
   # This makes secondValue = -1 when there is only one numeral left
   # so firstNum is always "at least" secondNum when len(ns) == 1. 
   secondNum = numberOfNumeral(ns[1]) if len(ns) > 1 else -1
   if firstNum is at least secondNum:
      # Add firstNum to total.
      # Remove the character - so that the loop state advances.
      # If we don't don't his, as in the original, it will never end.
      # Here we use "slice notation".
      ns = ns[1:] 
   else:
      # Add the difference, secondNum - firstNum, to total.
      # Remove both characters - again, so we advance state.
      ns = ns[2:]
Run Code Online (Sandbox Code Playgroud)