我的函数在以下输入interpret(["NOT", "true"], {"NOT": "false"})处失败
基本上,该函数用于“创建我自己的”逻辑值操作符,并在列表中的值与字典中的键匹配时解释它们。我在这里找到了KeyError: "true",但我不知道如何修复它。
我是不是做错了递归?它应该返回"false“,因为" not”在这种情况下等于"false“,但在其他情况下,它应该作为正常的not运算符函数运行,如果你明白我的意思的话。
我的函数的代码:
def interpret(logicalExpression, interpretation):
if type(logicalExpression) is str: #
if not interpretation:
return logicalExpression
return interpretation[logicalExpression]
elif len(logicalExpression) == 1:
return interpret(logicalExpression[0], interpretation)
elif logicalExpression[1] == "OR" and len(logicalExpression) >= 3:
if interpret(logicalExpression[0], interpretation) == "true" or interpret(logicalExpression[2:], interpretation) == "true":
return "true"
else:
return "false"
elif logicalExpression[1] == "AND" and len(logicalExpression) >= 3:
if interpret(logicalExpression[0], interpretation) == "true" and interpret(logicalExpression[2:], interpretation) == "true":
return "true"
else:
return "false"
if logicalExpression[0] == "NOT" and len(logicalExpression) == 2:
if interpret(logicalExpression[1:], interpretation) == "false":
return "true"
else:
return "false"发布于 2017-10-09 21:18:20
错误在您的输入中。
在logicalExpression中传递"true",但在解释中不传递"true"。KeyError是正确的行为。
我认为你想通过像{"true": "true", "false": "false"}这样的解释
>>> interpret(["NOT", "true"], {"true": "true", "false": "false"})
'false'https://stackoverflow.com/questions/46645643
复制相似问题