Solving expression containing the multiple NOTs

I want to run the program with multiple NOT in the statement but not able to do that. Suppose I wrote the equation as NOT TRUE and pass it into the variables as ["NOT", "TRUE"], then I am able to get the right answer that is ["FALSE"]. Now when I am passing variables as ["NOT", "NOT", "TRUE"] then I am getting the output is ["TRUE","TRUE"] but it should be ["TRUE"].

What changes need to be done in the code below?

def implement_not(variable):
    pos_minus = variable.index('NOT')

    if (variable[pos_minus + 1] == 'TRUE'):
        variable[pos_minus + 1] = 'FALSE'
    else:
        variable[pos_minus + 1] = 'TRUE'
    del variable[pos_minus]
    return variable

Answer

You have two problems here – the first is that you need to search from the end, rather than the beginning, because in NOT NOT TRUE, the second one should be evaluated first. The second problem is that you shouldn’t assume that everything that isn’t TRUE is FALSE. This code fixes both problems.

def implement_not(variable):
    pos_minus = len(variable) - variable[::-1].index('NOT') - 1
    
    if variable[pos_minus + 1] == 'TRUE':
        variable[pos_minus + 1] = 'FALSE'
        del variable[pos_minus]
    elif variable[pos_minus + 1] == 'FALSE':
        variable[pos_minus + 1] = 'TRUE'
        del variable[pos_minus]
    return variable

It’s also probably good to note that this method mutates the list, so it’s not really necessary to return it, because the caller already has a reference to it. You also might need to call it multiple times to handle all of the NOTs, so it might be useful to instead return a status code for whether it needs to be called again.

Leave a Reply

Your email address will not be published. Required fields are marked *