Search code examples
pythontruthtable

Truth Table. Printing the sum of each True value for each row in the desired format


I'm able to sum up the value of each True statement per row, but I can't get it to print in a column format next to the result.

 `res = eval(exp)  # evaluate the logical input from the user
 print(res)  # this prints the result of the logical expression in a column format`

This section of the code evaluates my logical expression from the user input and prints the True/False result in a column format as desired. However, I can't figure out how to display my sum of each row's Truth value in the same format. Underneath this code I sum up each row of the truth table, but can only get it to print at the bottom of my result. Below is how I am summing up each row.

   `try:
    res = eval(exp)  # evaluate the logical input from the user
    print(res)  # this prints the result of the logical expression in a column format

        truth_sum = []  # I create this list
        for row in truth_table:  # I parse the each row in the truth table
            truth_sum.append(sum(row))  # and sum up each True statement
    except:
        print("Wrong Expression")
print(*truth_sum, sep="\n")  # This line is my problem.  I can't figure how to print this next to each result
print()`

If I place the print(*truth_sum, sep="\n")above the except: it prints it out after each Truth Table row. How would I get the sum list to print out next to the logical expression column? Here is my complete code for better understanding.

`import itertools
truth_table = 0
val = 0
exp = ''
p1 = 0
p2 = 0
p3 = 0
p4 = 0
p5 = 0
p6 = 0
pos = 0


# This function takes care of taking users input
def get_input():
    global val
    while True:
        try:
            val = int(input("Please Enter the number of parameters, 1 - 5: "))
            if val < 1 or val > 5:
            print(f"Enter a value [0,6)")
        else:
            break
        except ValueError:
            print(f"Only Numbers are Allowed, Try Again..")


# This function takes care of the Truth Table header
def table_header():
    print("========================TRUTH TABLE===============================")
    print("p1\t\t\tp2\t\t\tp3\t\t\tp4\t\t\tp5")
    print("*" * 20 * val)


# This is the Main method
def main():
    # Global Variables
    global val
    global truth_table
    global exp
    global p1
    global p2
    global p3
    global p4
    global p5
    global pos

    # Call the userInput Function
    get_input()

    # Creating the truth table
    truth_table = list(itertools.product([True, False], repeat=val))
    exp = input("Enter a Logical Statement i.e [(p1 and p2) or p3]: [p1==p2==p3==...Pn:]:").lower()

    # printing Table Layout
    table_header()
    for par in truth_table:
        pos = 0
        if val == 1:
            p1 = par[0]
        elif val == 2:
            p1, p2 = par[0], par[1]
        elif val == 3:
            p1, p2, p3 = par[0], par[1], par[2]
        elif val == 4:
            p1, p2, p3, p4 = par[0], par[1], par[2], par[3]
        else:
            p1, p2, p3, p4, p5 = par[0], par[1], par[2], par[3], par[4]
            pos = 0
        while pos < val:
            print(par[pos], end='\t\t')
            pos = pos + 1
        try:
            res = eval(exp)  # evaluate the logical input from the user
            print(res)  # this prints the result of the logical expression in a column format

            truth_sum = []  # I create this list
            for row in truth_table:  # I parse the each row in the truth table
                truth_sum.append(sum(row))  # and sum up each True statement
        except:
            print("Wrong Expression")
    print(*truth_sum, sep="\n")  # This line is my problem.  I can't figure how to print this next to 
                                   each result
    print()


if __name__ == "__main__":
    main()` 

Here is an example of my output.

`Please Enter the number of parameters, 1 - 5: 2
Enter a Logical Statement i.e [(p1 and p2) or p3]: [p1==p2==p3==...Pn:]:p1 and p2
========================TRUTH TABLE===============================
p1          p2          p3          p4          p5
****************************************
True        True        True
True        False       False
False       True        False
False       False       False
2
1
1
0`

How do I get this sum list of each row of True values to display next to the logical expression result instead of at the bottom?


Solution

  • I've written here the version of the code I'd write for this task avoiding the eval() method (as suggested by Chris Doyle) and adopting the main idea of saving the data in RAM before to print anything. In this way you can then print it as you prefer.

    The following code is "minimized" in order to be understood. Therefore some stuff is not included (e.g. the table header). Anyway you can add it then easily.

    import itertools
    
    # Hard-coded expression to evaluate the parameters of the truth table
    EXPRESSION = lambda array: array[0] and array[1]
    PARAMETERS_NUMBER = 2
    # function to count the total number of true in a row
    TRUE_COUNTER = lambda array: sum([int(x==True) for x in array])
    
    truth_table = list(itertools.product([True, False], repeat=PARAMETERS_NUMBER))
    
    # array with the result of the truth table for each row
    results = [EXPRESSION(row) for row in truth_table]
    # array with the number of true for each parameter row
    true_numbers = [TRUE_COUNTER(row) for row in truth_table]
    
    # print the table
    for row, result, true_number in zip(truth_table, results, true_numbers):
        print(row, result, true_number, "\n")
    

    Let me know if it is enough clear and useful for your task.