python将阿拉伯数字转换为罗马数字的方法

本文实例讲述了python将阿拉伯数字转换为罗马数字的方法。分享给大家供大家参考。具体实现方法如下:

def numtoromannum(num):
“””digital will be converted into roman numerals,ex: numtoromannum(3999)”””
if num < 1 or num > 3999:
print ‘the num must in 1-3999’
else:
numdic = {
‘1’:(‘i’,’iv’,’v’,’ix’),
‘2’:(‘x’,’xl’,’l’,’xc’),
‘3’:(‘c’,’cd’,’d’,’cm’),
‘4’:(‘m’)
}
items = sorted(numdic.items())
retstr = ”
for item in items:
str = ”
(num,modnum) = pmod(num,10)
if modnum != 0:
if item[0] != ‘4’:
if modnum 0:
str = str.join([”,item[1][0]])
modnum -= 1
elif modnum < 5: str = item[1][1] elif modnum == 5: str = item[1][2] elif modnum < 9: str = item[1][2] while modnum > 5:
str = str.join([”,item[1][0]])
modnum -= 1
else:
str = item[1][3]
else:
while modnum > 0:
str = str.join([”,item[1][0]])
modnum -= 1
retstr = str.join([”,retstr])
return retstr

希望本文所述对大家的python程序设计有所帮助。