Python:生成罗马序号I、II、III

需求:将阿拉伯数字1,2,3,...转成罗马数字I,II,III,...



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

# Generate 10 Roman numerals
num_to_generate = 10
roman_numerals_list = generate_roman_numerals(num_to_generate)

# Print the generated Roman numerals
for i, numeral in enumerate(roman_numerals_list, start=1):
    print(f"{i}. {numeral}")
    

输出结果:

1. I

2. II

3. III

4. IV

5. V

6. VI

7. VII

8. VIII

9. IX

10. X

你可能感兴趣的:(Python,python)