Bird
Raised Fist0

Consider the following pseudocode implementing the Interpreter pattern:

medium📝 Analysis Q4 of Q15
LLD - Behavioral Design Patterns — Part 2
Consider the following pseudocode implementing the Interpreter pattern:
class TerminalExpression:
    def __init__(self, value):
        self.value = value
    def interpret(self, context):
        return self.value == context

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)

context = 'X'
expr = AndExpression(TerminalExpression('X'), TerminalExpression('Y'))
print(expr.interpret(context))
What will be the output of this code?
AFalse
BTrue
CNone
DError at runtime
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate TerminalExpression('X').interpret('X')

    This returns True because 'X' == 'X'.
  2. Step 2: Evaluate TerminalExpression('Y').interpret('X')

    This returns False because 'Y' != 'X'.
  3. Step 3: Evaluate AndExpression.interpret('X')

    Returns True AND False which is False.
  4. Final Answer:

    False -> Option A
  5. Quick Check:

    Both expressions must be true for AND [OK]
Quick Trick: AND returns true only if both expressions are true [OK]
Common Mistakes:
MISTAKES
  • Assuming OR logic instead of AND
  • Confusing context with expression value
  • Ignoring the return value of interpret methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes