Python Programming on Roman numerals converted to Arabic numerals
Arabic notation as a traditional method of counting position, wants to be a Roman numeral conversion is a difficult thing, the law of the Roman numeral I summarized as follows:
- Same digital ligatures, equal to the number indicated by the numbers obtained by adding the number ( at most three ligatures )
- Small numbers of large numbers on the right side, is equal to the number indicated by the number obtained by adding the numbers
- A low number ( limited Ⅰ, X and C ) the number of large numbers on the left, equal to the number represented by the reduced number of large numbers obtained
Therefore, with the len function , conventional loop and judgment statement, the basis of print, input and other functions, I successfully edited out of this program.
Code is as follows :( can learn, plagiarism is strictly prohibited )
#阿拉伯数字转换罗马数字1~3999
#I=1 V=5 X=10 L=50 C=100 D=500 M=1000 IV=4 IX=9 XL=40 XC=90 CD=400 CM=900
#在构成数字的时候,有下列规则:
#1、相同的数字连写,所表示的数等于这些数字相加得到的数
#2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数
#3、小的数字,(限于Ⅰ、X和C)在大的数字的左边,所表示的数等于大数减小数得到的数
print('''--------------------------------------------------
作者:20192428魏来
阿拉伯数字向罗马数字的转换
--------------------------------------------------''')
list = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
a = 0
while a < 9999 : #多次进行转换:(9998次)
a = a+1
romannum = input('''--------------------------------------------------
请输入罗马数字(输入范围:1-3999):''')
result = 0
omit = -1 # omit为需省略的字符位
if romannum in list:
print(list[romannum])
else:
for b in range(len(romannum)): # 遍历字符串的每一位:(0,len-1)
if b == omit: # 如果无需省略b
pass
elif b <= len(romannum)-2: # 如果还没有遍历到最后一位:(len-1-1)
if list[romannum[b]] < list[romannum[b+1]]: # 如果前一位对应值小于后一位的
result += list[romannum[b+1]] - list[romannum[b]] # 进行减操作
omit = b+1 # 省略下一位字符
else:
result += list[romannum[b]]
else: # 遍历到最后一位
result += list[romannum[b]]
print('''对应阿拉伯数字为:{}
--------------------------------------------------'''.format(result))