I am working on a project, one part of it is to generate a truth table for a given boolean expression ( such as: (A NOT B) NOR (C OR D)). I could not find a built in bitwise operator for NOR gate, so I wrote a code of my own for it, which works good with simple expressions. But if brackets are introduced for unambiguity and false results, the code does a terrible job. [for example, for the expression mentioned above, it gives an output of (a~b~()|()c|d)] Here is the code snippet:
# to replace NOR gate with bitwise NOR operation of ~(var_a | var_b)
for m in range(0,len(expression)):
v=len(expression)
for v in range(0,len(expression)):
if (expression[v]=="!"):
prev='~(' + expression[v-1]
nextt=expression[v+1]+')'
replacement= prev + "|" + nextt
leftear= expression[:v-1]
rightear=expression[v+2:]
print('left right ears:',leftear,rightear)
expression= leftear+replacement+rightear
print('expression refined= X= ',expression)
The only solution that I found on google was to write a parse tree (which python says that, it has been deprecated so we are recommended to use AST). I am a total beginner and search out a little bit about parse trees, but I wanted to ask: 1)Is the AST or parsers the only way to do it? Are there any built in functions for it in python? 2) Whats the better way of handeling NOR gate ?
astmodule can parse Python code. If the only non-Python syntax isNOR, you can try to extend Python syntax a little. Which syntax are you required to parse? Just one example(A NOT B) NOR (C OR D))doesn't show it all. Are you required to parseXOR? Any Python expression, including arithmetic? Also, what operator precedence should you use (e.g. how to parseNOT A AND B)? The answer to these questions will affect the decision of whether or not to useast. Also, what doesA NOT Bmean?