Search code examples
pythonpython-3.xroman-numerals

Arabic number to Roman Numeral Converter: Number containing 4 will not convert


Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.

I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to test with different combination of numbers. The codes before the one below pretty much determine how many thousands, five hundreds, hundreds, etc that is in the number inputted. Could anyone help me?

def display_roman(M, D, C, L, X, V, I):

    CM = 0
    CD = 0
    XC = 0
    XL = 0
    IX = 0
    IV = 0

    if D == 2:
        M += 1
        D -= 2
    elif L == 2:
        C += 1
        L -= 2
    elif V == 2:
        X += 1
        V -= 2

    if V == 1 and I == 4:
        V = 0
        I = 0
        IX = 1
    elif I == 4:
        I == 0
        IV == 1
    if X == 4:
        X == 0
        XL == 1
    if L == 1 and X == 4:
        L == 0
        X == 0
        XC == 1
    if C == 4:
        C == 0
        CD == 1
    if D == 1 and C == 4:
        D == 0
        C == 0
        CM == 1

    print("The roman numeral of your number is: ")
    print("M" * M, "CM" * CM, "D" * D, "CD" * CD, "C" * C,"XC" * XC, "L" * L, "XL" * XL, "X" * X, "IX" * IX, "V" * V, "IV" * IV, "I" * I)

If I input numbers like 4 or 14, I expect to get IV and XIV respectively. But the actual outputs are IIII and XIIII respectively.

Please help. I'm sorry if there is something wrong with the format of my question as I am also new to stackoverflow. Thank you in advance.


Solution

  • Welcome to SO! The problem is the way you are trying to define and change your variables. For example, this piece of code:

       elif I == 4:
           I == 0
           IV == 1
    

    should look like this instead:

       elif I == 4:
           I = 0
           IV = 1
    

    == is a boolean Operator that will return True if two values are the same and False if they are not. = is the correct way to assign a new value to a variable. After changing this, all works as intended.


    display_roman(0, 0, 0, 0, 0, 0, 4)
    display_roman(0, 0, 0, 0, 0, 1, 4)
    
    The roman numeral of your number is: 
           IV 
    The roman numeral of your number is: 
         IX