Truth Tables in Python

Harold Nelson

9/19/2019

The Conclusion

I suggested a way to write a python program to come to a conclusion about the equivalence of two logical expressions. Here it is.

tv = [True,False]
# Initialize empty lists
rl = [] 
sl = []

# Loop through possible values of p and q
for p in tv:
    for q in tv:
        r = not p and not q
        s = not(p or q)
        
        # Append truth values for current p, q values
        rl.append(r)
        sl.append(s)
        
# Determine conclusion
if r == s:
    conclusion = "Yes - Equivalent"
else:
    conclusion = "No - Not Equivalent"
    
print(conclusion)
## Yes - Equivalent

Generalization

The code above works well, but it would be better if one did not have to examine the code to see where to modify it to use different logical expressions. Could we rewrite this as a function? How can we supply the logical expressions as arguments?

Answer


def compare(f,g):
    
    # Note that f and g are functions.
    
    tv = [True,False]
    # Initialize empty lists
    rl = [] 
    sl = []

    # Loop through possible values of p and q
    for p in tv:
        for q in tv:
            r = f(p,q)
            s = g(p,q)

            # Append truth values for current p, q values
            rl.append(r)
            sl.append(s)

    # Determine conclusion
    if r == s:
        conclusion = "Yes - Equivalent"
    else:
        conclusion = "No - Not Equivalent"

    return conclusion

Exercise

Let’s try this. We need two functions which return logical values.

Answer

def f1(a,b):
    return not a and not b
def f2(c,d):

    return not(c or d)
    
compare(f1,f2)    
## 'Yes - Equivalent'