Bird
0
0

What will be the output of this code snippet using the Interpreter pattern?

medium📝 Analysis Q5 of 15
LLD - Behavioral Design Patterns — Part 2
What will be the output of this code snippet using the Interpreter pattern?
class AndExpression:
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2
    def interpret(self, context):
        return self.expr1.interpret(context) and self.expr2.interpret(context)

class TerminalExpression:
    def __init__(self, data):
        self.data = data
    def interpret(self, context):
        return self.data == context

expr = AndExpression(TerminalExpression('A'), TerminalExpression('B'))
print(expr.interpret('A'))
ATrue
BFalse
CError
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand AndExpression interpret logic

    It returns True only if both sub-expressions interpret to True.
  2. Step 2: Evaluate sub-expressions with context 'A'

    TerminalExpression('A').interpret('A') is True, TerminalExpression('B').interpret('A') is False, so overall False.
  3. Final Answer:

    False -> Option B
  4. Quick Check:

    AndExpression with one False sub-expression = False [OK]
Quick Trick: AndExpression returns True only if both expressions are True [OK]
Common Mistakes:
MISTAKES
  • Assuming only one expression needs to be True
  • Ignoring second expression result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes