坚持将整数转换为罗马数

Stuck at converting integers into romans

我正在尝试使用 for 循环将整数转换为罗马数字。我启动了代码,但我目前被困在这里,我不知道该怎么办(一直出错)。如果有人对如何继续此代码有任何想法,将不胜感激。

roman_digits = {1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: 'V', 4: "IV", 1: "I"}

empty = ""
rand_num = 153

for nums, alpha in roman_digits.items():
    if rand_num <= nums:
        empty += alpha
        rand_num -= nums

print(empty)

此代码无效

您的算法需要在某个时候更改输入数字的值。例如,对于像 1053 这样的输入,在第一次迭代中你会发现 M。此时您不再对 1000 地方感兴趣 — 您需要休息 — 53。因此,您可以将 M 添加到输出中并继续寻找 53。然后找到L,继续找3。像这样的事情可能会让它朝着好的方向发展:

def rn(rand_num):
    empty = ""

    while rand_num > 0:
        for nums, alpha in roman_digits.items():
            if rand_num >= nums:
                empty += alpha
                rand_num -= nums  # change rand_nums
                break

    return empty

我改编了我发现 HERE 的代码,使其在 class 之外工作。逻辑都在网站上解释了。

rand_num = 153

val = [
    1000, 900, 500, 400,
    100, 90, 50, 40,
    10, 9, 5, 4,
    1
    ]
syb = [
    "M", "CM", "D", "CD",
    "C", "XC", "L", "XL",
    "X", "IX", "V", "IV",
    "I"
    ]
roman_num = ''
i = 0
while  rand_num > 0:
    for _ in range(rand_num // val[i]):
        roman_num += syb[i]
        rand_num -= val[i]
    i += 1
print(roman_num)