diff --git a/seminar/tests.py b/seminar/tests.py index 4e2193ad..2a22d721 100644 --- a/seminar/tests.py +++ b/seminar/tests.py @@ -11,6 +11,7 @@ from django.core.management import call_command from seminar.models import Skola, Resitel, Rocnik, Cislo, Problem, Reseni, PrilohaReseni, Soustredeni, Nastaveni from seminar.testutils import create_test_data from seminar import ovvpfile +from seminar import utils class SeminarBasicTests(TestCase): def setUp(self): @@ -72,4 +73,9 @@ class SeminarBasicTests(TestCase): t = o.to_string() assert t == filetext + def test_roman(self): + for i in [0, 1, 23, 2015, 1999, 42, 4, 400, 78, 4321, 8765, 999]: + r = utils.roman(i) + fr = utils.from_roman(r) + assert fr == i diff --git a/seminar/utils.py b/seminar/utils.py index 26b23750..a4a4027a 100644 --- a/seminar/utils.py +++ b/seminar/utils.py @@ -1,12 +1,20 @@ # -*- coding: utf-8 -*- +roman_numerals = zip((1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1), + ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')) + def roman(num): - 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') res = "" - for i, n in zip(ints, nums): + for i, n in roman_numerals: res += n * (num // i) num %= i return res +def from_roman(rom): + if not rom: + return 0 + for i, n in roman_numerals: + if rom.upper().startswith(n): + return i + from_roman(rom[len(n):]) + raise Exception('Invalid roman numeral: "%s"', rom)