[python] Q1
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- import itertools
- def generate_truth_table(proposition):
- variables = sorted(set([char for char in proposition if char.isalpha()]))
- num_vars = len(variables)
- # Generate all possible combinations of truth values for the variables
- truth_values = list(itertools.product([True, False], repeat=num_vars))
- # Print column headers
- print('\t'.join(variables + [proposition]))
- # Print truth values
- for values in truth_values:
- eval_str = proposition
- for var, val in zip(variables, values):
- eval_str = eval_str.replace(var, str(val))
- print('\t'.join(str(val) for val in values + [eval(eval_str)]))
- # Propositions
- prop_a = "(p and not q) xor r"
- prop_b = "p and not q"
- prop_c = "p or q"
- # Generate and print truth tables
- print("Truth table for (a) (p and not q) xor r:")
- generate_truth_table(prop_a)
- print("\nTruth table for (b) p and not q:")
- generate_truth_table(prop_b)
- print("\nTruth table for (c) p or q:")
- generate_truth_table(prop_c)
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:
Latest Code Pastes