public
Created

  • Download Gist
RomanNumberCalculator.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
def getRoman(number):
res = ""
 
numbersAsStringArray = str(number)
 
if (len(numbersAsStringArray) >= 4):
thousands = int(numbersAsStringArray[-4])
res += getThousands(thousands)
if (len(numbersAsStringArray) >= 3):
hundreds = int(numbersAsStringArray[-3])
res += getHundreds(hundreds)
if (len(numbersAsStringArray) >= 2):
tens = int(numbersAsStringArray[-2])
res += getTens(tens)
if (len(numbersAsStringArray) >= 1):
ones = int(numbersAsStringArray[-1])
res += getOnes(ones)
return res
 
def getThousands(num):
# alt fra 1000 til 3000
res = ""
 
if num >= 1 and num <= 3:
for x in xrange(num):
res += "M"
return res
 
 
def getHundreds(num):
return getNum(num, "C", "D", "M")
 
def getTens(num):
return getNum(num, "X", "L", "C")
def getOnes(num):
return getNum(num, "I", "V", "X")
 
def getNum(num, low, mid, high):
res = ""
 
if (num == 9):
res += low + high
elif (num == 5):
res += mid
elif (num > 5):
res += mid
for x in xrange(0, num - 5):
res += low
elif (num == 4):
res += low + mid
elif(num > 0 and num <= 3):
for x in xrange(0,num):
res += low
 
return res
 
if __name__ == "__main__":
print(getRoman(4))
print(getRoman(0004))
print(getRoman(904))
print(getRoman(1904))
print(getRoman(1904))
print(getRoman(1954))
print(getRoman(1984))
print(getRoman(1997))
print(getRoman(1999))
print(getRoman(2008))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.