Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple script that uses .eval() function to evaluate an expression containing boolean values.
'''
Logic expression evaluation.
Examples:
1) a and b or c
2) a and (c or (c and d and e))
3) ((b and c) and c) or a
'''
# to replace, eq: and -> &
connector = {'and':'&', 'or':'|'}
print('')
expr = input("Enter your expression: ")
expr = expr.replace(' ', '')
for k,v in connector.items():
expr = expr.replace(k,v)
# replace &,|,(,) dengan comma ,
split = ['&', '|', '(', ')']
expr_copy = expr[:]
for s in split:
expr_copy = expr_copy.replace(s, ',')
# cari semua single vars
var = []
for c in expr_copy.split(','):
if c.isalpha():
if c not in var:
var.append(c)
print("List of variables : ", end='')
print(var)
print('')
# possible input 2^n
n = 2**len(var)
for i in range(n):
# https://stackoverflow.com/questions/699866/python-int-to-binary
binary = "{0:b}".format(i)
# padding zero
binary = binary.zfill(len(var))
new_expr = expr[:]
for i,v in enumerate(var):
new_expr = new_expr.replace(var[i], binary[i])
# convert back to original expression
for k,v in connector.items():
new_expr = new_expr.replace(v, ' {} '.format(k))
output = eval(new_expr)
output = int(output)
print("Evaluate ({}) => {}".format(new_expr, output))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment