为Python中的任何表达式创建真值表 [英] Creating a truth table for any expression in Python

查看:120
本文介绍了为Python中的任何表达式创建真值表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,该程序在运行时将询问布尔表达式,变量,然后为输入的内容创建一个真值表.我需要使用一门课,这是我到目前为止的内容.我不确定从这里去哪里.

I am attempting to create a program that when run will ask for the boolean expression, the variables and then create a truth table for whatever is entered. I need to use a class and this is what I have so far. I am not sure where to go from here.

from itertools import product

class Boolean(object):

       def __init__(self, statement, vars):
           self.exp = statement
           self.vars = vars

       def __call__(self, statement, vars):

def main():
   expression = raw_input('Give an expression:')
   vars = raw_input('Give names of variables:')
   variables = vars.split(' ')
   b = Boolean(expression, variables)

if __name__ == "__main__":
   main()

推荐答案

我有一个完全可以满足您需求的库! 查看 github存储库或找到它

I have a library that does exactly what you want! Check out the github repo or find it here on pypi.

自述文件描述了一切工作原理,但这是一个简单的示例:

The readme describes how everything works, but here's a quick example:

from truths import Truths
print Truths(['a', 'b', 'x', 'd'], ['(a and b)', 'a and b or x', 'a and (b or x) or d'])
+---+---+---+---+-----------+--------------+---------------------+
| a | b | x | d | (a and b) | a and b or x | a and (b or x) or d |
+---+---+---+---+-----------+--------------+---------------------+
| 0 | 0 | 0 | 0 |     0     |      0       |          0          |
| 0 | 0 | 0 | 1 |     0     |      0       |          1          |
| 0 | 0 | 1 | 0 |     0     |      1       |          0          |
| 0 | 0 | 1 | 1 |     0     |      1       |          1          |
| 0 | 1 | 0 | 0 |     0     |      0       |          0          |
| 0 | 1 | 0 | 1 |     0     |      0       |          1          |
| 0 | 1 | 1 | 0 |     0     |      1       |          0          |
| 0 | 1 | 1 | 1 |     0     |      1       |          1          |
| 1 | 0 | 0 | 0 |     0     |      0       |          0          |
| 1 | 0 | 0 | 1 |     0     |      0       |          1          |
| 1 | 0 | 1 | 0 |     0     |      1       |          1          |
| 1 | 0 | 1 | 1 |     0     |      1       |          1          |
| 1 | 1 | 0 | 0 |     1     |      1       |          1          |
| 1 | 1 | 0 | 1 |     1     |      1       |          1          |
| 1 | 1 | 1 | 0 |     1     |      1       |          1          |
| 1 | 1 | 1 | 1 |     1     |      1       |          1          |
+---+---+---+---+-----------+--------------+---------------------+

希望这会有所帮助!

这篇关于为Python中的任何表达式创建真值表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆