X-Git-Url: https://git.mdrn.pl/librarian.git/blobdiff_plain/fefdce4e24f9e397df5538fe6e7f54b5ece4d841..8550d172b829f29b2fcd4723789fb2a5d9fff6eb:/src/librarian/util.py diff --git a/src/librarian/util.py b/src/librarian/util.py index c302084..5c9fbc2 100644 --- a/src/librarian/util.py +++ b/src/librarian/util.py @@ -1,10 +1,11 @@ -# Functions to convert between integers and Roman numerals. Doctest examples included. -# by Paul Winkler +# Functions to convert between integers and Roman numerals. +# by Paul Winkler # http://code.activestate.com/recipes/81611-roman-numerals/ # PSFL (GPL compatible) from __future__ import print_function, unicode_literals import os +import six def int_to_roman(input): @@ -51,12 +52,13 @@ def int_to_roman(input): >>> print(int_to_roman(1999)) MCMXCIX """ - if type(input) != type(1): + if not isinstance(input, int): 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') + 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]) @@ -64,10 +66,11 @@ def int_to_roman(input): input -= ints[i] * count return result + def roman_to_int(input): """ Convert a roman numeral to an integer. - + >>> r = list(range(1, 4000)) >>> nums = [int_to_roman(i) for i in r] >>> ints = [roman_to_int(n) for n in nums] @@ -91,21 +94,21 @@ def roman_to_int(input): ... ValueError: input is not a valid roman numeral: IL """ - if type(input) != type(""): + if not isinstance(input, six.text_type): raise TypeError("expected string, got %s" % type(input)) input = input.upper() nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I'] ints = [1000, 500, 100, 50, 10, 5, 1] places = [] for c in input: - if not c in nums: + if c not in nums: raise ValueError("input is not a valid roman numeral: %s" % input) for i in range(len(input)): c = input[i] value = ints[nums.index(c)] # If the next place holds a larger number, this value is negative. try: - nextvalue = ints[nums.index(input[i +1])] + nextvalue = ints[nums.index(input[i + 1])] if nextvalue > value: value *= -1 except IndexError: @@ -113,7 +116,8 @@ def roman_to_int(input): pass places.append(value) sum = 0 - for n in places: sum += n + for n in places: + sum += n # Easiest test for validity... if int_to_roman(sum) == input: return sum