function int_to_roman
Converts an integer between 1 and 3999 to its Roman numeral string representation.
/tf/active/vicechatdev/patches/util.py
1106 - 1118
simple
Purpose
This function provides a mathematical conversion utility that transforms decimal integers into their Roman numeral equivalents. It uses a subtractive notation approach (e.g., IV for 4, IX for 9) and is useful for formatting numbers in classical Roman style for display purposes, document numbering, or educational applications.
Source Code
def int_to_roman(input):
if type(input) != type(1):
raise TypeError("expected integer, got %s" % type(input))
if not 0 < input < 4000:
raise ValueError("Argument must be between 1 and 3999")
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result = ""
for i in range(len(ints)):
count = int(input / ints[i])
result += nums[i] * count
input -= ints[i] * count
return result
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
input |
- | - | positional_or_keyword |
Parameter Details
input: An integer value that must be between 1 and 3999 (inclusive). The function validates that the parameter is of integer type and within the valid range. Values outside this range or non-integer types will raise exceptions.
Return Value
Returns a string containing the Roman numeral representation of the input integer. The string consists of Roman numeral characters (M, D, C, L, X, V, I) and their subtractive combinations (CM, CD, XC, XL, IX, IV). For example, 1994 returns 'MCMXCIV'.
Usage Example
# Basic usage
result = int_to_roman(1994)
print(result) # Output: 'MCMXCIV'
# More examples
print(int_to_roman(1)) # Output: 'I'
print(int_to_roman(58)) # Output: 'LVIII'
print(int_to_roman(3999)) # Output: 'MMMCMXCIX'
# Error handling
try:
int_to_roman(4000) # Raises ValueError
except ValueError as e:
print(f"Error: {e}")
try:
int_to_roman("123") # Raises TypeError
except TypeError as e:
print(f"Error: {e}")
Best Practices
- Always validate input is within the range 1-3999 before calling, or handle ValueError exceptions appropriately
- Ensure input is an integer type; the function will raise TypeError for other types including float
- The function modifies the input parameter internally during calculation, but this doesn't affect the caller since integers are immutable in Python
- For large-scale conversions, consider caching results if the same values are converted repeatedly
- This implementation uses standard subtractive notation (e.g., IV for 4, not IIII)
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function int_to_alpha 56.9% similar
-
function _int_to_bytes 52.0% similar
-
function dt_to_int 41.2% similar
-
function make_path_unique 40.8% similar
-
function _generate_document_number_fallback 39.3% similar