문제

I'm trying to implement a stack which holds operators and numbers. The operators can be, among others: not, and, or. The operators are matched against regular expressions:

expression = '(( NOT (2 <= 4)) OR (2 = 2))'
log_op = re.compile('NOT|AND|OR|not|and|or')
log_match = log_op.match(expression)

if log_match is not None:
    operator_stack.push(log_match.group().lower())

Now i need to take some action if I pop one of these operators from the stack:

operator = operator_stack.pop()
if operator is "not":
    # invert some True to False

The problem here is that it never enters the if. I'm not sure if the problem is that the match object doesn't compare to a string.

도움이 되었습니까?

해결책

First off, match literally matches the entire string to see if it matches the expression, which it clearly does not. Lastly, if you are trying to parse the entire input expression as such, it should be parsed into an abstract syntax tree - a stack will probably not represent the intended expression unless you ignore order of operations or have some other ways to compensate for this. Correcting the last one is out of the scope of this question.

To find a value, you want to use search

As an aside, there is an operator module which you may consider looking into.

>>> log_op.match(expression)
>>> log_op.search(expression)
<_sre.SRE_Match object at 0x22068b8>

Note that match returned nothing, but search did, so we will use that, and see how you compare that

>>> log_op.search(expression).group().lower()
'not'
>>> log_op.search(expression).group().lower() is "not"
False
>>> log_op.search(expression).group().lower() == "not"
True

As str objects are instantiated, they won't have the same identity as other instances even if values are equal, so you have to compare using an equality comparison as that comparison operator is implemented for those objects in the typically expected manner.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top