Bird
0
0

Given the following code snippet, what will be the output after calling undo() on the last command?

medium📝 Analysis Q13 of 15
LLD - Design — Tic-Tac-Toe Game
Given the following code snippet, what will be the output after calling undo() on the last command?
class AddCommand:
    def __init__(self, value, receiver):
        self.value = value
        self.receiver = receiver
    def execute(self):
        self.receiver.total += self.value
    def undo(self):
        self.receiver.total -= self.value

class Receiver:
    def __init__(self):
        self.total = 0

receiver = Receiver()
cmd1 = AddCommand(5, receiver)
cmd2 = AddCommand(3, receiver)
cmd1.execute()
cmd2.execute()
cmd2.undo()
print(receiver.total)
A5
B8
C3
D0
Step-by-Step Solution
Solution:
  1. Step 1: Trace command executions

    Initially, receiver.total = 0. After cmd1.execute(), total = 0 + 5 = 5. After cmd2.execute(), total = 5 + 3 = 8.
  2. Step 2: Apply undo on cmd2

    cmd2.undo() subtracts 3, so total = 8 - 3 = 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Execute adds, undo subtracts = 5 [OK]
Quick Trick: Undo reverses last execute effect on total [OK]
Common Mistakes:
MISTAKES
  • Forgetting to subtract on undo
  • Assuming undo resets total to zero
  • Mixing order of execute and undo

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes