首页 > 编程知识 正文

Python罗马数字转换,将整数转换成字符串python

时间:2023-05-03 15:14:38 阅读:242451 作者:23

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

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

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。