用python将罗马数字转换为整数

2024-09-29 23:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是继user2486之后我现在的代码。

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()

当ns: unbundlocalerror:赋值前引用的局部变量'ns'


Tags: 代码mapmaindefcdcmtotalix
3条回答

不需要重新发明轮子(除非你愿意)。Python附带一个转换器:

import roman;
n=roman.fromRoman("X"); #n becomes 10

如果您需要它的数字5000及以上,您将需要编写一个新的函数,不过,也许您自己的字体来表示线超过罗马数字。(这只会对一些数字起作用。停在4999是个好主意。)

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

其他人实际上链接到了roman模块在上面的一条注释中使用的相同源代码,但我不相信他们提到它实际上是随Python一起提供的。

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

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

如果一个值低于下面的值,它将被减去。否则将被添加。

例如,我们要将罗马数字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.

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

1000 - 100 + 1000 + 50 - 1 + 5 = 1954 

参考号: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

考虑一下这个额外的伪代码和提示(有些是有效的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:]

相关问题 更多 >

    热门问题