You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python根据后缀表达式生成真值表变量顺序错误问题求助

问题修复方案

问题根因

原有代码存在两处逻辑导致输出不符合预期:

  • 表头直接按后缀表达式的字符顺序打印,变量顺序完全跟随后缀表达式中变量出现顺序,输入RPQ&|时R第一个出现,因此表头首列为R
  • 变量收集后未做排序,生成取值映射的顺序和变量出现顺序一致,和预期的P、Q、R字母升序顺序不符

修改后完整代码

while True:
    x = input("\n\nEnter Calculation: ").upper()

    # 收集变量、去重并按字母升序排序
    vars = []
    for i in x:
        if i.isalpha() and not i in vars:
            vars.append(i)
    vars.sort()  # 排序后变量顺序为P、Q、R
    
    # 打印表头:先打排序后的变量,再打运算符列(不需要中间步骤可删除后面的运算符打印)
    print(' '.join(vars), end=' ')
    for i in x:
        if not i.isalpha():
            print(i, end=' ')

    for i in range(2**len(vars)):
        print('')
        string = bin(i)[2:].rjust(len(vars),'0')
        bools = list(map(lambda x: True if x=='1' else False, string))
        a = dict(zip(vars,bools))
        
        # 先打印当前行排序后的变量取值
        print(' '.join(str(int(b)) for b in bools), end=' ')
        
        math = []
        for j in x:
            if j.isalpha():
                math.append(a[j])
            elif j == '&':
                math[-2] = math[-2] & math[-1]
                print(int(math[-2]),end=' ')
                del math[-1]
            elif j == '|':
                math[-2] = math[-2] | math[-1]
                print(int(math[-2]),end=' ')
                del math[-1]
            elif j == '^':
                math[-2] = math[-2] ^ math[-1]
                print(int(math[-2]),end=' ')
                del math[-1]
            elif j == '>':
                math[-2] = math[-2] <= math[-1]
                print(int(math[-2]),end=' ')
                del math[-1]
            elif j == '<':
                math[-2] = math[-2] >= math[-1]
                print(int(math[-2]),end=' ')
                del math[-1]
            elif j == '!' or j == '~' or j == '`':
                math[-1] = not math[-1]
                print(int(math[-1]),end=' ')
            else:
                print("Error: Invalid Character")

可选优化:只保留变量+最终结果输出

如果不需要展示中间运算步骤,只需要变量和最终表达式结果,可以把运算过程中的打印逻辑去掉,运算完成后统一打印最终结果即可,修改运算部分代码如下:

math = []
        for j in x:
            if j.isalpha():
                math.append(a[j])
            elif j == '&':
                math[-2] = math[-2] & math[-1]
                del math[-1]
            elif j == '|':
                math[-2] = math[-2] | math[-1]
                del math[-1]
            # 其余运算符逻辑保持不变,仅删除内部的print语句
            # ...
        # 运算完成后打印最终结果
        print(int(math[0]), end=' ')

内容的提问来源于stack exchange,提问作者Briik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:54:01