使用python输出真值表

本文介绍如何使用Python创建一个类来解析表达式,并通过递归函数生成真值表。通过处理输入字符串,利用eval()和exec()函数避免复杂的括号匹配,简化代码实现。
摘要由CSDN通过智能技术生成

首先创建一个类,利用python自身的优势对表达式进行解析

# &为合取,v为析取,~为非,>为条件联结词,*为双条件联结词
class Variable:
    def __init__(self, value=0):
        self.value = value
    # 返回两个对象的合取
    def __and__(self, other):# 对 & 运算符的定义
        return Variable(1) if (self.value==1 and other.value==1) else Variable(0)
    def __or__(self, other):# 对 | 运算符的定义
        return Variable(0) if self.value==other.value==0 else Variable(1)
    # 对象的条件连接
    def __gt__(self, other):# 对 > 运算符的定义
        return Variable(0) if (self.value==1 and other.value==0) else Variable(1)
    # 对象的取反
    def __invert__(self):# 对 ~ 运算符的定义
        return Variable(1) if self.value==0 else Variable(0)
    # 对象的双条件连接
    def __mul__(self, other):# 对 * 运算符的定义
        return Variable(1) if self.value==other.value else Variable(0)
    def __str__(self):# 对打印显示的重载
        return str(
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值