1 # Functions to convert between integers and Roman numerals. Doctest examples included.
3 # http://code.activestate.com/recipes/81611-roman-numerals/
4 # PSFL (GPL compatible)
8 def int_to_roman(input):
10 Convert an integer to Roman numerals.
14 Traceback (most recent call last):
15 ValueError: Argument must be between 1 and 3999
18 Traceback (most recent call last):
19 ValueError: Argument must be between 1 and 3999
22 Traceback (most recent call last):
23 TypeError: expected integer, got <type 'float'>
25 >>> for i in range(1, 21): print int_to_roman(i)
47 >>> print int_to_roman(2000)
49 >>> print int_to_roman(1999)
52 if type(input) != type(1):
53 raise TypeError, "expected integer, got %s" % type(input)
54 if not 0 < input < 4000:
55 raise ValueError, "Argument must be between 1 and 3999"
56 ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
57 nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
59 for i in range(len(ints)):
60 count = int(input / ints[i])
61 result += nums[i] * count
62 input -= ints[i] * count
65 def roman_to_int(input):
67 Convert a roman numeral to an integer.
69 >>> r = range(1, 4000)
70 >>> nums = [int_to_roman(i) for i in r]
71 >>> ints = [roman_to_int(n) for n in nums]
75 >>> roman_to_int('VVVIV')
76 Traceback (most recent call last):
78 ValueError: input is not a valid roman numeral: VVVIV
80 Traceback (most recent call last):
82 TypeError: expected string, got <type 'int'>
84 Traceback (most recent call last):
86 ValueError: input is not a valid roman numeral: A
87 >>> roman_to_int('IL')
88 Traceback (most recent call last):
90 ValueError: input is not a valid roman numeral: IL
92 if type(input) != type(""):
93 raise TypeError, "expected string, got %s" % type(input)
95 nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
96 ints = [1000, 500, 100, 50, 10, 5, 1]
100 raise ValueError, "input is not a valid roman numeral: %s" % input
101 for i in range(len(input)):
103 value = ints[nums.index(c)]
104 # If the next place holds a larger number, this value is negative.
106 nextvalue = ints[nums.index(input[i +1])]
107 if nextvalue > value:
110 # there is no next place.
114 for n in places: sum += n
115 # Easiest test for validity...
116 if int_to_roman(sum) == input:
119 raise ValueError, 'input is not a valid roman numeral: %s' % input
123 if not os.path.isdir(path):