Skip to content

Instantly share code, notes, and snippets.

@defrindr
Last active September 29, 2019 16:28
Show Gist options
  • Save defrindr/853ae6090dc203f69c25c9994bf7b8fe to your computer and use it in GitHub Desktop.
Save defrindr/853ae6090dc203f69c25c9994bf7b8fe to your computer and use it in GitHub Desktop.
Converter Roman - Decimal with python
# Created function to convert num to roman
def dec2rom(num):
_m = int(num / 1000)
num = num % 1000
#
_d = int(num / 500)
num = num % 500
#
_c = int(num / 100)
num = num % 100
#
_l = int(num / 50)
num = num % 50
#
_x = int(num / 10)
num = num % 10
#
_v = int(num / 5)
num = num % 5
# generate result
result = ("M"*_m)+("D"*_d)+("C"*_c)+("L"*_l)+("X"*_x)+("V"*_v)+("I"*num)
# replace result
result = result.replace("DCCCC","CM")
result = result.replace("LXXXX","XC")
result = result.replace("VIIII","IX")
result = result.replace("CCCC","CD")
result = result.replace("XXXX","XL")
result = result.replace("IIII","IV")
print(result) # print result
pass
def rom2dec(string):
# set string to uppercase
string = string.upper()
#
romanTable = {
'CM':900,
'XM':990,
'IM':999,
'M':1000,
'CD':400,
'XD':490,
'ID':499,
'D':500,
'XC':90,
'IC':99,
'C':100,
'XL':40,
'IL':49,
'L':50,
'IX':9,
'X':10,
'IV':4,
'V':5,
'I':1,
}
# string.replace()
for key in romanTable: # get key
if key in string: # if key exist
string =string.replace(key,f" {romanTable.get(key)}") #replace
pass
pass
print(sum(int(s) for s in string.split()))
pass
#dec2rom(1999)
#rom2dec("mMXiX")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment