在python中将罗马数字转换为整数

在python中将罗马数字转换为整数,第1张

在python中将罗马数字转换为整数

考虑一下此附加的伪代码和提示(其中一些是有效的Python,一些不是有效的,但有注释)。

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:]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5644877.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存