Python程式將整數轉換為羅馬數字
羅馬數字起源於古羅馬的一種數字系統。它們在整個羅馬帝國廣泛使用,並在今天某些情況下仍在使用。羅馬數字基於拉丁字母的組合來表示數值。
羅馬數字中使用的基本符號如下:
I: 1 V: 5 X: 10 L: 50 C: 100 D: 500 M: 1000
為了構成更大的數字,這些符號以各種方式組合。以下規則適用:
符號通常從左到右按值遞減的順序書寫。
如果較小值的符號出現在較大值的符號之前,則較小值被減去。例如,IV 表示 4(5 - 1),IX 表示 9(10 - 1)。
如果較小值的符號出現在較大值的符號之後,則較小值被加到較大值上。例如,VI 表示 6(5 + 1),XI 表示 11(10 + 1)。
一個符號最多可以連續重複三次來表示該值的加法。例如,III 表示 3(1 + 1 + 1),XXX 表示 30(10 + 10 + 10)。
放在符號上方的橫線將它的值乘以 1000。例如,V̄ 表示 5000。
將整數轉換為羅馬數字時,一般過程是找到小於或等於給定數字的最大符號,並將其新增到羅馬數字表示中。重複此過程以計算餘數,直到整個數字被轉換。
在本文中,我們將看到將整數轉換為羅馬數字的不同方法。
方法
以下是將整數轉換為羅馬數字的步驟:
定義羅馬數字符號及其對應的值。這些符號包括 I、V、X、L、C、D 和 M,分別表示 1、5、10、50、100、500 和 1000。
從一個空字串開始,用於儲存羅馬數字表示。
從最大值到最小值迭代符號。
檢查當前符號的值是否小於或等於給定的整數。
如果是,則從整數中減去符號的值,並將符號追加到羅馬數字字串。
噹噹前符號的值仍然小於或等於剩餘整數時,重複上述步驟。
轉到下一個符號,並重復步驟 5 和 6,直到所有符號都已檢查。
返回羅馬數字字串。
使用元組列表
此方法使用列表來儲存羅馬數字符號及其對應的值,表示為元組。
示例
這是一個將整數轉換為相應的羅馬數字的 Python 程式。
def integer_to_roman(num):
symbols = [
(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')
]
roman = ''
for value, symbol in symbols:
while num >= value:
roman += symbol
num -= value
return roman
# Define the input integer
number = 14
print('Input integer number:',number)
roman_numeral = integer_to_roman(number)
print(f"The Roman numeral representation of {number} is: {roman_numeral}")
輸出
Input integer number: 14 The Roman numeral representation of 14 is: XIV
使用字典
此方法使用 Python 字典資料結構來儲存羅馬數字符號及其對應的值,表示為鍵值對。
示例
讓我們看看下面使用字典將整數轉換為其相應羅馬數字的示例。
def integer_to_roman(num):
symbols = {
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'}
roman = ''
for value in sorted(symbols.keys(), reverse=True):
while num >= value:
roman += symbols[value]
num -= value
return roman
# Define the input integer
number = 231
print('Input integer number:',number)
roman_numeral = integer_to_roman(number)
print(f"The Roman numeral representation of {number} is: {roman_numeral}")
輸出
Input integer number: 231 The Roman numeral representation of 231 is: CCXXXI
使用roman庫
要在 Python 中將整數轉換為羅馬數字,可以使用 roman 庫。為此,我們首先需要使用 pip 命令安裝該庫 **(pip install roman)**。安裝完成後,可以使用 roman 庫中的 toRoman() 函式將整數轉換為其對應的羅馬數字。
示例
在這個例子中,我們將使用 toRoman() 函式將數字 123 轉換為其羅馬數字表示。
# import the roman module
import roman
def integer_to_roman(num):
return roman.toRoman(number)
# Define the input integer
number = 121
print('Input integer number:',number)
roman_numeral = integer_to_roman(number)
print(f"The Roman numeral representation of {number} is: {roman_numeral}")
輸出
Input integer number: 121 The Roman numeral representation of 121 is: CXXI
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP