Converting Roman Numerals to integers in python

前端 未结 17 1606
挽巷
挽巷 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:08

    Consider this additional pseudo-code and hints (some of it is valid Python, some isn't, but there be notes).

    def numberOfNumeral(n):
        """ Return the number represented by the single numeral """
        # e.g. "v" -> 5, "i" -> 5 (and handle v/V cases, etc.)
    
    # avoid "string" as a variable name
    # I chose "ns" for "numerals" (which might be better),
    # but I'm also a bit terse .. anyway, name variables for what they represents.
    ns = str(input("Enter a roman numeral"))
    
    while ns:
       firstNum = numberOfNumeral(ns[0])
       # This makes secondValue = -1 when there is only one numeral left
       # so firstNum is always "at least" secondNum when len(ns) == 1. 
       secondNum = numberOfNumeral(ns[1]) if len(ns) > 1 else -1
       if firstNum is at least secondNum:
          # Add firstNum to total.
          # Remove the character - so that the loop state advances.
          # If we don't don't his, as in the original, it will never end.
          # Here we use "slice notation".
          ns = ns[1:] 
       else:
          # Add the difference, secondNum - firstNum, to total.
          # Remove both characters - again, so we advance state.
          ns = ns[2:]
    
    • Explain Python's slice notation
    • Does Python have a ternary conditional operator?

提交回复
热议问题