Last active
September 18, 2019 09:12
-
-
Save Syncrossus/b7301121f2bb2bedb44a44d8f4bed6c3 to your computer and use it in GitHub Desktop.
This is an attempt at making the most concise roman numeral "solver" possible using recursivity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from numpy import argmax | |
translate = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000 | |
} | |
def is_valid(sequence): | |
""" Checks that a sequence of numbers is valid according | |
to the rules of Roman numeral notation. | |
Is incomplete, accepts some invalid numbers. | |
Args: | |
sequence (list<int>): a Roman numeral but with each letter | |
replaced by its arabic numeral counterpart. | |
Returns: | |
valid (bool): whether the Roman numeral is valid or not | |
""" | |
for i in range(1, len(sequence)): | |
if sequence[i] / sequence[i - 1] > 10: | |
return False | |
return True | |
def solve(sequence): | |
""" Converts a Roman numeral to a traditional integer. | |
Args: | |
sequence (list<int>): a Roman numeral but with each letter | |
replaced by its arabic numeral counterpart. | |
Returns: | |
number (int): the number represented by the Roman numeral | |
""" | |
if len(sequence) == 0: | |
return 0 | |
pivot = argmax(sequence) | |
number = (sequence[pivot] + | |
solve(sequence[pivot + 1:]) - | |
solve(sequence[:pivot])) | |
return number | |
if __name__ == '__main__': | |
roman = sys.argv[1] | |
arab = [translate[i] for i in roman] | |
assert is_valid(arab) | |
print(solve(arab)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is released under the .