在递归遍历列表并将值与字典匹配时出现键错误,Python

2024-07-05 15:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的函数在以下输入处失败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"

Tags: and函数falsetruelenreturnifnot
1条回答
网友
1楼 · 发布于 2024-07-05 15:51:38

输入错误。

逻辑表达式中传递"true",但在解释中不传递"true"KeyError是正确的行为。你知道吗

我想你应该像{"true": "true", "false": "false"}那样通过口译

>>> interpret(["NOT", "true"], {"true": "true", "false": "false"})
'false'

相关问题 更多 >