-1

inputing an logical expression as string and evaluating, i'm getting proper output

str1 = "(1|0)&(1|1&(0|1))"
print eval(str1)
o/p: 1

But the same way if i'm including not operator as ~, the output goes wrong.

str1 = "(~0|~1)&(~1|0)"
print eval(str1)
o/p: -2

Is there any other way of representing not operator here to get proper answer.

3 Answers3

1

These are not logical expressions but bitwise expressions. That is the reason why ~0 == -1. Instead you can look for a parser that parses these expressions the way you want. A quick google search showed up this stackoverflow question. Sympy seems to implement a similar thing: sympy logic

The logic module for SymPy allows to form and manipulate logic expressions using symbolic and boolean values

syntonym
  • 7,134
  • 2
  • 32
  • 45
0

&, | and ~ are bitwise operators.

For logic operators use and, or and not.

If your intention is to do logical operations, prefer to use the appropriate boolean values:

True / False

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0
str1 = "(not 0|not 1) and (not 1|0)"
print eval(str1)

In python NOT is not

Ref : https://docs.python.org/2/library/stdtypes.html

backtrack
  • 7,996
  • 5
  • 52
  • 99