Converting Roman Numerals to integers in python

前端 未结 17 1601
挽巷
挽巷 2020-12-03 03:56

This is now my current code after what user2486 said.

def romanMap():
    map=((\"M\",  1000),(\"CM\", 900),(\"D\",  500),(\"CD\", 400),(\"C\",  100),(\"XC\"         


        
17条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 04:24

    Okay, there are a lot of things wrong with what you currently have.

    First, the reason you are getting a bunch of 0's is because you are never exiting your while string != "": loop, and it isn't ever adding integers to the total. So total remains zero, and keeps getting printed. I've commented the code you posted to help you understand what is going on.

    def main():
        string=str(input("Enter a roman numeral"))
        total=0
        while string != "": # Empty strings evaluate as False, this can just be 'while string:'
            if string[1] == string[2] or string == len([1]): # Here you are testing the 2nd and 3rd elements.
                                                             # Also, you want to do len(string) == 1
                                                             # string will never == len([1]), so you never
                                                             # execute the code in this block.
                total += string[1]+1   # You want to add the corresponding value of string[0], use a dictionary.
            print (total)
    
            # Missing the else statement in the pseudocode.
    main()
    

    user2864740 has some good comments in their posted solution, look over that to see some of the things you were doing wrong.

    Here is Python (2.7 unfortunately) code that does what your given pseudocode says.

    val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    
    def main():
        string = str(raw_input('Enter a roman numeral: '))
        string = string.upper()
        total = 0
        while string:
            if len(string) == 1 or val[string[0]] >= val[string[1]]:
                total += val[string[0]]
                string = string[1:]
            else:
                total += val[string[1]] - val[string[0]]
                string = string[2:]
        print total
    
    main()
    

    Please note that the pseudocode you posted is NOT correct. Note what it will do for the input 'IIV'. It will subtract 1 from 1, then add 5. But what it should do is subtract 2 from 5.

提交回复
热议问题