[python] Q1

Viewer

  1. import itertools
  2.  
  3. def generate_truth_table(proposition):
  4.     variables = sorted(set([char for char in proposition if char.isalpha()]))
  5.     num_vars = len(variables)
  6.     
  7.     # Generate all possible combinations of truth values for the variables
  8.     truth_values = list(itertools.product([True, False], repeat=num_vars))
  9.  
  10.     # Print column headers
  11.     print('\t'.join(variables + [proposition]))
  12.  
  13.     # Print truth values
  14.     for values in truth_values:
  15.         eval_str = proposition
  16.         for var, val in zip(variables, values):
  17.             eval_str = eval_str.replace(var, str(val))
  18.         print('\t'.join(str(val) for val in values + [eval(eval_str)]))
  19.  
  20. # Propositions
  21. prop_a = "(p and not q) xor r"
  22. prop_b = "p and not q"
  23. prop_c = "p or q"
  24.  
  25. # Generate and print truth tables
  26. print("Truth table for (a) (p and not q) xor r:")
  27. generate_truth_table(prop_a)
  28.  
  29. print("\nTruth table for (b) p and not q:")
  30. generate_truth_table(prop_b)
  31.  
  32. print("\nTruth table for (c) p or q:")
  33. generate_truth_table(prop_c)
  34.  

Editor

You can edit this paste and save as new:


File Description
  • Q1
  • Paste Code
  • 05 May-2024
  • 1.01 Kb
You can Share it: