Answer to Question #95724 in Python for Gustavo Dias

Question #95724
What are some examples of casual (and incorrect) use of AND and OR decisions? As a programmer, how might you ensure that the problem is well defined before you start coding
1
Expert's answer
2019-10-02T08:04:33-0400

A decision structure is a construct in a computer program that allows the program to make a decision and change its behaviour based on that decision. The decision is made based on the outcome of a logical test. A logical test is a calculation whose outcome is either true or false.

Casual (and incorrect) use of AND and OR decisions may lead to an error when running the program. We can use one of two useful logical transformation rules known as DeMorgan's laws to simplify the situation. Given two logical propositions A and B, DeMorgan's laws allow us to simplify certain expressions involving negations and logical combinations of these:


"not \\ (A \\ and \\ B) \u21d4 (not \\ A) \\ or \\ (not \\ B) \\\\\nnot \\ (A \\ or \\ B) \u21d4 (not \\ A) \\ and \\ (not \\ B)"

However, when working with such decisions, in addition to logical errors, errors may occur with the priority of the operators of the selected programming language. Let's demonstrate this errors using the Python programming language as an example. Below is the code for both DeMorgan's laws.

A = True
B = True
x = not(A and B) == (not A) or (not B)
y = not(A or B) == (not A) and (not B)
print(x, y)

This returns:

True False

An error of the second decision is observed. This is caused by different priority operators.

In Python, the == operator has higher priority than not. The expression not a == b is read as not (a == b) rather than (not a) == b, because the former is usually more useful than the latter. Therefore, y should look like:

y = (not(A or B)) == ((not A) and (not B))

And x should look like:

x = (not(A and B)) == ((not A) or (not B))

Then we'll get the right results. (Our x is also wrong, and is getting a True result for the wrong reasons: it's actually evaluating (not ((A and B) == (not A)) or (not B) which works out to (not (True == False)) or False which works out to True or False. But what we actually wanted was (not (A and B)) == ((not A) or (not B)), which works out to (not True) == (False or False), which works out to False == False. Our x is getting a True result for the wrong reasons.)


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS