将整数转换为罗马数字

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

罗马数字是一种起源于古罗马的数字系统。如今,它们仍在各种场合中使用,例如书籍章节编号和电影续集编号。在这个挑战中,你将负责创建一个函数,将1到3999(含)之间的整数转换为其罗马数字表示形式。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13734{{"将整数转换为罗马数字"}} python/for_loops -.-> lab-13734{{"将整数转换为罗马数字"}} python/lists -.-> lab-13734{{"将整数转换为罗马数字"}} python/tuples -.-> lab-13734{{"将整数转换为罗马数字"}} python/function_definition -.-> lab-13734{{"将整数转换为罗马数字"}} python/build_in_functions -.-> lab-13734{{"将整数转换为罗马数字"}} end

整数转罗马数字

编写一个函数 to_roman_numeral(num),它接受一个介于1到3999(含)之间的整数 num,并返回其作为字符串的罗马数字表示形式。

要将整数转换为其罗马数字表示形式,你可以使用一个查找列表,其中包含以(罗马数字值,整数)形式的元组。然后,你可以使用 for 循环遍历查找列表中的值,并使用 divmod() 用余数更新 num,将罗马数字表示形式添加到结果中。

你的函数应返回输入整数的罗马数字表示形式。

def to_roman_numeral(num):
  lookup = [
    (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'),
  ]
  res = ''
  for (n, roman) in lookup:
    (d, num) = divmod(num, n)
    res += roman * d
  return res
to_roman_numeral(3) ## 'III'
to_roman_numeral(11) ## 'XI'
to_roman_numeral(1998) ## 'MCMXCVIII'

总结

在这个挑战中,你学习了如何将整数转换为其罗马数字表示形式。你使用了一个包含(罗马数字值,整数)形式元组的查找列表,并使用 for 循环遍历查找列表中的值。你还使用 divmod() 用余数更新 num,将罗马数字表示形式添加到结果中。