logo

Question detail

A programmer writes the following Python function to return True when exactly two of three switches are on.\n\ndef exactly_two(a, b, c):\n return (a and b) or c\n\na) Explain why this solution is incorrect.\nb) Give a corrected Boolean expression for the return statement.\nc) Describe a systematic way to check that the corrected solution works.

Try the question, check the answer, then read the explanation to understand the curriculum point.

At a glance

Question

Type

practice

Style

Topic

Abstraction and automation

Exam-style question

Try this first

A programmer writes the following Python function to return True when exactly two of three switches are on.\n\ndef exactly_two(a, b, c):\n return (a and b) or c\n\na) Explain why this solution is incorrect.\nb) Give a corrected Boolean expression for the return statement.\nc) Describe a systematic way to check that the corrected solution works.

Model answer

What a good answer should say

  • a) The expression returns True whenever c is True, even if neither a nor b is True or if all three switches are True.
  • It therefore does not require exactly two true inputs.
  • b) A corrected expression is (a and b and not c) or (a and c and not b) or (b and c and not a).
  • c) List and test all eight possible combinations of three Boolean inputs.

Explanation

Why this works

For exactly two true inputs, the solution must identify each possible pair and explicitly require that the remaining input is false. Three Boolean inputs have 2^3 = 8 combinations, so checking all eight combinations provides a complete check for this problem.

Common mistake

No common mistake is linked to this question yet.

Related flashcards

No flashcards are published for this page yet.

Related practice questions

No questions are published for this page yet.