CS FundamentalsHardProduct-company placement · Python

What value does this Command pattern code print?

What value does this Command pattern code print?
v = [0]
class Add:
    def __init__(s, n): s.n = n
    def do(s): v[0] += s.n
    def undo(s): v[0] -= s.n

undo, redo = [], []
def run(c): c.do(); undo.append(c); redo.clear()
def u():
    c = undo.pop(); c.undo(); redo.append(c)
def r():
    if redo:
        c = redo.pop(); c.do(); undo.append(c)

run(Add(5)); run(Add(3)); u(); run(Add(10)); r(); u(); r()
print(v[0])
  1. A. 18
  2. B. 15
  3. C. 5
  4. D. 8

Correct answer: B. 15

5, then 8; undo gives 5 with redo = [Add(3)]; running Add(10) gives 15 and clears redo, so the next r() does nothing; undo removes 10 (5) and redo puts it back (15). Expecting the cleared Add(3) to come back gives 18.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic