【发布时间】:2014-05-17 03:58:25
【问题描述】:
我需要将罗马数字字符串转换为整数。我什至不知道如何开始,只是我需要使用正则表达式。
import re
def romanNumeralToInt(romanNum):
romanNum = romanNum.upper()
totalValue = 0
我确实有一系列测试应该通过:
def test():
print("Tests started.")
x = "III"
"" if romanNumeralToInt(x) == 3 else print(x + " - " + str(romanNumeralToInt(x)))
x = "IV"
"" if romanNumeralToInt(x) == 4 else print(x + " - " + str(romanNumeralToInt(x)))
x = "IX"
"" if romanNumeralToInt(x) == 9 else print(x + " - " + str(romanNumeralToInt(x)))
x = "C"
"" if romanNumeralToInt(x) == 100 else print(x + " - " + str(romanNumeralToInt(x)))
x = "CC"
"" if romanNumeralToInt(x) == 200 else print(x + " - " + str(romanNumeralToInt(x)))
x = "CCC"
"" if romanNumeralToInt(x) == 300 else print(x + " - " + str(romanNumeralToInt(x)))
x = "CD"
"" if romanNumeralToInt(x) == 400 else print(x + " - " + str(romanNumeralToInt(x)))
x = "D"
"" if romanNumeralToInt(x) == 500 else print(x + " - " + str(romanNumeralToInt(x)))
x = "DC"
"" if romanNumeralToInt(x) == 600 else print(x + " - " + str(romanNumeralToInt(x)))
x = "DCC"
"" if romanNumeralToInt(x) == 700 else print(x + " - " + str(romanNumeralToInt(x)))
x = "DCCC"
"" if romanNumeralToInt(x) == 800 else print(x + " - " + str(romanNumeralToInt(x)))
x = "M"
"" if romanNumeralToInt(x) == 1000 else print(x + " - " + str(romanNumeralToInt(x)))
x = "LXI"
"" if romanNumeralToInt(x) == 61 else print(x + " - " + str(romanNumeralToInt(x)))
x = "IC"
"" if romanNumeralToInt(x) == 99 else print(x + " - " + str(romanNumeralToInt(x)))
x = "MMCI"
"" if romanNumeralToInt(x) == 2101 else print(x + " - " + str(romanNumeralToInt(x)))
print("Tests ended.")
【问题讨论】:
-
到目前为止你有什么?一个好的起点是在维基百科上查看如何手动转换这些,然后尝试编写你正在做的事情。如果您只是在寻找执行此操作的代码,谷歌搜索,一切都结束了。
-
@U2EF1 我试过了,我找不到任何使用正则表达式的例子
-
您“需要”使用正则表达式是因为您认为这是最好的方法(我不同意)还是因为它是作业的一部分?
-
@Kryptos 你知道如何使用正则表达式吗?也许你可以看看文档。
-
我知道“如何”在一般情况下使用正则表达式,但我无法弄清楚具体数字,是的,我需要使用正则表达式