Advertisement
Guest User

Untitled

a guest
Apr 16th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1.  
  2. import re
  3.  
  4. # to replace, eq: and -> &
  5. connector = {'and':'&', 'or':'|'}
  6.  
  7. print('')
  8. expr = input("Enter your expression: ")
  9.  
  10. expr = expr.replace(' ', '')
  11. for k,v in connector.items():
  12.     expr = expr.replace(k,v)
  13.  
  14. # cari semua single vars
  15. var = []
  16. for c in expr:
  17.     if c.isalpha():
  18.         if c not in var:
  19.             var.append(c)
  20.  
  21. print("List of variable : ", end='')
  22. print(var)
  23. print('')
  24.  
  25. # possible input 2^n
  26. n = 2**len(var)
  27.  
  28. for i in range(n):
  29.  
  30.     # https://stackoverflow.com/questions/699866/python-int-to-binary
  31.     binary = "{0:b}".format(i)
  32.  
  33.     # padding zero
  34.     binary = binary.zfill(len(var))
  35.  
  36.     new_expr = expr[:]
  37.     for i,v in enumerate(var):
  38.         new_expr = new_expr.replace(var[i], binary[i])
  39.  
  40.     # convert back to original expression
  41.     for k,v in connector.items():
  42.         new_expr = new_expr.replace(v, ' {} '.format(k))
  43.  
  44.     output = eval(new_expr)
  45.     output = int(output)
  46.  
  47.     print("Evaluate ({}) => {}".format(new_expr, output))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement