#!/usr/bin/env python3
'''
thousands - 0 to 3 Ms
hundreds - 900 (CM),400 (CD),0-300 (0 to 3 Cs),
or 500-800 (D,followed by 0 to 3 Cs)
tens - 90 (XC),40 (XL),0-30 (0 to 3 Xs)
or 50-80 (L,followed by 0 to 3 Xs)
ones - 9 (IX),4 (IV),0-3 (0 to 3 Is)
or 5-8 (V,fowllowed by 0 to 3 Is)
the range of the number need to be converted is 1-3999
'''
import re
def isRoman(num):
pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})'
if re.search(pattern, num):
return 1
else:
return 0
def arabic2roman(num):
if num > 3999 or num < 1:
print('num is out of range (1-3999)')
return
dict = {
0: ('', 'M', 'MM', 'MMM'),
1: ('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'),
2: ('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'),
3: ('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX')
}
roman = ''
roman += dict[0][num // 1000 % 10]
roman += dict[1][num // 100 % 10]
roman += dict[2][num // 10 % 10]
roman += dict[3][num % 10]
return roman
def roman2arabic(roman):
if isRoman(roman) == 0:
print('it is not a valid roman number !')
return
num = 0
dict = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
for i in range(len(roman)-1):
if dict[roman[i]] < dict[roman[i+1]]:
num -= dict[roman[i]]
else:
num += dict[roman[i]]
return num+dict[roman[-1]]
羅馬數(shù)字與阿拉伯?dāng)?shù)字相互轉(zhuǎn)換
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- LeetCode題目:Integer to RomanRoman to Integer 羅馬數(shù)字規(guī)則 羅馬數(shù)字共有...
- 五年后,你想成為一個什么樣的人? 五年后,你會怎么來決策現(xiàn)在要做的事情? 五年后,你會告訴現(xiàn)在的自己應(yīng)該關(guān)注哪些事...