简体   繁体   中英

Boolean Truth Table by using Python

I am so new to Python, so I really need help with this question. I tried so many time, but can't get it. Any suggestions would be appreciated. Thanks

def xor(a,b):
      return (a and not b) or (not a and b)

Write a function that returns the truth table for xor in dictionary form. You should be using xor() inside the function below

def xorTruthTable():

 return {}

The output should be like this:

The truth table for "and" in dictionary form is

{(False, False) : False, \
(False, True)  : False, \
(True,  False) : False, \
(True,  True)  : True}

You can do this with a nested loop. We'll loop through all the possible values of a (in this case, False and True ), and for each of those we'll again loop through all the possible values of b . Whatever code we write in the inner loop will get run for every possible combination of a and b .

We'll keep track of a table (a dict , or {} ) to hold these values. For each combination of a and b , we'll add the tuple (a, b) as a key, and xor(a, b) as the value for that key. Then we can just return the dictionary.

def truth_table():
    table = {}
    for a in [False, True]:
        for b in [False, True]:
            table[(a, b)] = xor(a, b)
    return table

Here is a concise solution using itertools.product to generate the four possible input pairs and a dictionary comprehension to create the dictionary from them. operator.xor is a library function that happens to do the same as your xor function

{(i, j): operator.xor(i, j) for i, j in itertools.product((False, True), repeat=2)}
# Output:
# {(False, False): False, (False, True): True, (True, False): True, (True, True): False}

A 1-line solution using Python's ^ operator:

{(a,b): a^b for a in (True,False) for b in (True,False)}

If you wanted to use your xor() :

{(a,b): xor(a,b) for a in (True,False) for b in (True,False)}

Either would evaluate to

{(False, True): True, (True, False): True, (False, False): False, (True, True): False}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM