如何将整数转换为罗马数字?

How to convert an integer into a roman numeral?

我无法将一个整数转换为罗马数字,因为我有一个带方括号的整数输出(我很确定它是一个列表,但我想要的是一个整数)我不能'找不到解决方案,为什么我在 'rom' 值上有 'None'。 我正在使用 python3.

roman.py

#!/usr/bin/env python3

import sys

def numToRom(number):
    rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

    if number in range(0, 9):
       result = rom[number]
       return result

num = sys.argv[1:]
rom = numToRom(num)
print(num, " is ", rom)

$ ./roman.py 2

旧输出:

['2'] is None

期望的输出:

2 is II

你的问题源于你将一个包含一个字符的列表传递给你的函数。该函数需要一个整数 (if number in range(0, 9)),因此您需要将其转换为正确的整数。

import sys

def numToRom(number):
    if type(number) is list: # If you know your number might be a list with only one str(value)
        number = int(number[0])
    
    rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

    if number in range(0, 9):
       result = rom[number]
       return result

如果 number 的形式为 ['{some digit}],那将专门针对您的用例。如果你想更有趣,你可以使用递归到 return 列表,列表中每个数字的罗马数字,如下所示:

def numToRom(number):
    if type(number) is list:
        rom = []
        for value in number:
            rom.append(numToRom(int(value)))
        return rom
    else:
        rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
    
        if number in range(0, 9):
           result = rom[number]
           return result

>>> num = ['2', '3', '5']
>>> numToRom(num)
    ['2', '3', '5']  is  ['III', 'IV', 'VI']

请注意,即使输入列表中的值不是字符,而是普通整数,此函数也能正常工作。

>>> num = [2, 3, 5]
>>> rom = numToRom(num)
    [2, 3, 5]  is  ['III', 'IV', 'VI']
  • pip install roman
import roman
print(roman.toRoman(int(input())))