Я могу суммировать значение каждого оператора True в строке, но не могу распечатать его в формате столбца рядом с результатом.
`res = eval(exp) # evaluate the logical input from the user
print(res) # this prints the result of the logical expression in a column format`
В этом разделе кода оценивается мое логическое выражение из пользовательского ввода и выводится результат True / False в формате столбца по желанию. Тем не менее, я не могу понять, как отобразить мою сумму значения Истины каждой строки в том же формате. Под этим кодом я суммирую каждую строку таблицы истинности, но могу только напечатать ее в нижней части моего результата. Ниже показано, как я суммирую каждую строку.
`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()`
Если я поставлю print(*truth_sum, sep="\n")
над except:
, он будет распечатан после каждой строки таблицы истинности. Как получить список сумм для печати рядом со столбцом логического выражения? Вот мой полный код для лучшего понимания.
`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()`
Вот пример моего вывода.
`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`
Как получить список сумм каждой строки значений True для отображения рядом с результатом логического выражения вместо at дно?