目标是创建一个程序,它将有效地让用户创建布尔逻辑语句(未启动),存储这些表达式,访问它们(expression_menu),构建它们(setup_table)然后评估它们(真值)然后最后测试他们(在另一个模块中)。
鉴于这一切,这对我的技能来说是一个相当大的项目。我坚持如何组织一切。我觉得我可能想要使用类,因为跟踪属性可能更容易......
然而我的问题是如何转移布尔逻辑语句,显然在第29行我将得到语法错误,因为x未定义(代码片段仅在第11行到第15行有意义。
我如何在此处整理代码以更好地适应我的目标
def setup_table(variables=2):
return (list(itertools.product(range(2), repeat = variables)))
def truth(variables=None,expression=None):
truth_table = []
for x in setup_table(variables):
if expression:
x.append(1)
else:
x.append(0)
truth_table.append(x)
return truth_table
def expression_menu():
expression = input('''
choose your expression:
1. if ((p and q) or (p or q)) and not(r or not q):
2. if (p or r) or (q and s):
3. if (p or r) and ( q or (p and s))
Expression: ''')
table = None
if int(expression) == 1:
table = truth(variables = 3, expression =((x[0] and x[1]) or (x[0] or x[1])) and not (x[
print(table)
if __name__ == "__main__":
import itertools
expression_menu()
答案 0 :(得分:1)
您可以将布尔表达式转换为函数。
所以:
table = truth(variables = 3, expression = lambda x: (x[0] and x[1]))
或:
def expression(x):
return x[0] and x[1]
table = truth(variables = 3, expression = expression)