Created
April 17, 2018 12:54
-
-
Save shahril96/9c0cf60f9c158f53304f3aff38b12d01 to your computer and use it in GitHub Desktop.
A simple script that uses .eval() function to evaluate an expression containing boolean values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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