Python 3.4-3.7 support;
[librarian.git] / librarian / util.py
1 # Functions to convert between integers and Roman numerals. Doctest examples included.
2 # by Paul Winkler 
3 # http://code.activestate.com/recipes/81611-roman-numerals/
4 # PSFL (GPL compatible)
5 from __future__ import print_function, unicode_literals
6
7 import os
8
9
10 def int_to_roman(input):
11     """
12     Convert an integer to Roman numerals.
13
14     Examples:
15     >>> int_to_roman(0)
16     Traceback (most recent call last):
17     ValueError: Argument must be between 1 and 3999
18
19     >>> int_to_roman(-1)
20     Traceback (most recent call last):
21     ValueError: Argument must be between 1 and 3999
22
23     >>> int_to_roman(1.5)  # doctest: +IGNORE_EXCEPTION_DETAIL
24     Traceback (most recent call last):
25     TypeError: expected integer, got <type 'float'>
26
27     >>> for i in range(1, 21): print(int_to_roman(i))
28     ...
29     I
30     II
31     III
32     IV
33     V
34     VI
35     VII
36     VIII
37     IX
38     X
39     XI
40     XII
41     XIII
42     XIV
43     XV
44     XVI
45     XVII
46     XVIII
47     XIX
48     XX
49     >>> print(int_to_roman(2000))
50     MM
51     >>> print(int_to_roman(1999))
52     MCMXCIX
53     """
54     if type(input) != type(1):
55         raise TypeError("expected integer, got %s" % type(input))
56     if not 0 < input < 4000:
57         raise ValueError("Argument must be between 1 and 3999")
58     ints = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,    5,  4,    1)
59     nums = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
60     result = ""
61     for i in range(len(ints)):
62         count = int(input / ints[i])
63         result += nums[i] * count
64         input -= ints[i] * count
65     return result
66
67 def roman_to_int(input):
68     """
69     Convert a roman numeral to an integer.
70     
71     >>> r = list(range(1, 4000))
72     >>> nums = [int_to_roman(i) for i in r]
73     >>> ints = [roman_to_int(n) for n in nums]
74     >>> print(r == ints)
75     1
76
77     >>> roman_to_int('VVVIV')
78     Traceback (most recent call last):
79      ...
80     ValueError: input is not a valid roman numeral: VVVIV
81     >>> roman_to_int(1)  # doctest: +IGNORE_EXCEPTION_DETAIL
82     Traceback (most recent call last):
83      ...
84     TypeError: expected string, got <type 'int'>
85     >>> roman_to_int('a')
86     Traceback (most recent call last):
87      ...
88     ValueError: input is not a valid roman numeral: A
89     >>> roman_to_int('IL')
90     Traceback (most recent call last):
91      ...
92     ValueError: input is not a valid roman numeral: IL
93     """
94     if type(input) != type(""):
95         raise TypeError("expected string, got %s" % type(input))
96     input = input.upper()
97     nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
98     ints = [1000, 500, 100, 50,  10,  5,    1]
99     places = []
100     for c in input:
101         if not c in nums:
102             raise ValueError("input is not a valid roman numeral: %s" % input)
103     for i in range(len(input)):
104         c = input[i]
105         value = ints[nums.index(c)]
106         # If the next place holds a larger number, this value is negative.
107         try:
108             nextvalue = ints[nums.index(input[i +1])]
109             if nextvalue > value:
110                 value *= -1
111         except IndexError:
112             # there is no next place.
113             pass
114         places.append(value)
115     sum = 0
116     for n in places: sum += n
117     # Easiest test for validity...
118     if int_to_roman(sum) == input:
119         return sum
120     else:
121         raise ValueError('input is not a valid roman numeral: %s' % input)
122
123
124 def makedirs(path):
125     if not os.path.isdir(path):
126         os.makedirs(path)