将整数转换为罗马数字的基本程序? [英] Basic program to convert integer to Roman numerals?
问题描述
我正在尝试编写一个代码,将用户输入的整数转换为其等效的罗马数字.到目前为止,我所拥有的是:
I'm trying to write a code that converts a user-inputted integer into its Roman numeral equivalent. What I have so far is:
generate_all_of_numeral
函数的重点在于它为每个特定数字创建一个字符串.例如,generate_all_of_numeral(2400, 'M', 2000)
将返回字符串 'MM'
.
The point of the generate_all_of_numeral
function is so that it creates a string for each specific numeral. For example, generate_all_of_numeral(2400, 'M', 2000)
would return the string 'MM'
.
我正在努力处理主程序.我首先找到 M 的罗马数字计数并将其保存到变量 M 中.然后我减去 M 的次数乘以符号值,得到下一个值来处理下一个最大的数字.
I'm struggling with the main program. I start off finding the Roman numeral count for M and saving that into the variable M. Then I subtract by the number of M's times the symbol value to give me the next value to work with for the next largest numeral.
对正确的方向有任何点头吗?现在我的代码甚至没有打印任何东西.
Any nod to the right direction? Right now my code doesn't even print anything.
推荐答案
处理此问题的最佳方法之一是使用 divmod
函数.您检查给定的数字是否与从最高到最低的任何罗马数字匹配.在每场比赛中,您都应该返回相应的字符.
One of the best ways to deal with this is using the divmod
function. You check if the given number matches any Roman numeral from the highest to the lowest. At every match, you should return the respective character.
有些数字在使用模函数时会有余数,因此您也对余数应用相同的逻辑.显然,我在暗示递归.
Some numbers will have remainders when you use the modulo function, so you also apply the same logic to the remainder. Obviously, I'm hinting at recursion.
请看下面我的回答.我使用 OrderedDict
来确保我可以向下"迭代列表,然后我使用 divmod
的递归来生成匹配.最后,我加入
所有生成的答案以产生一个字符串.
See my answer below. I use an OrderedDict
to make sure that I can iterate "downwards" the list, then I use a recursion of divmod
to generate matches. Finally, I join
all generated answers to produce a string.
from collections import OrderedDict
def write_roman(num):
roman = OrderedDict()
roman[1000] = "M"
roman[900] = "CM"
roman[500] = "D"
roman[400] = "CD"
roman[100] = "C"
roman[90] = "XC"
roman[50] = "L"
roman[40] = "XL"
roman[10] = "X"
roman[9] = "IX"
roman[5] = "V"
roman[4] = "IV"
roman[1] = "I"
def roman_num(num):
for r in roman.keys():
x, y = divmod(num, r)
yield roman[r] * x
num -= (r * x)
if num <= 0:
break
return "".join([a for a in roman_num(num)])
试一试:
num = 35
print write_roman(num)
# XXXV
num = 994
print write_roman(num)
# CMXCIV
num = 1995
print write_roman(num)
# MCMXCV
num = 2015
print write_roman(num)
# MMXV
这篇关于将整数转换为罗马数字的基本程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!