CS FundamentalsVery hardProduct-company placement · Python

In this Observer code, handler a unsubscribes itself the first time it runs. What does it print (lines joined by ' / ')?

In this Observer code, handler a unsubscribes itself the first time it runs. What does it print (lines joined by ' / ')?
class Bus:
    def __init__(self): self.subs = []
    def emit(self, e):
        for h in self.subs: h(e)

bus = Bus()
def a(e): print('a:' + e); bus.subs.remove(a)
def b(e): print('b:' + e)
def c(e): print('c:' + e)
bus.subs = [a, b, c]
bus.emit('x'); bus.emit('y')
  1. A. a:x / c:x / b:y / c:y
  2. B. a:x / b:x / c:x / b:y / c:y
  3. C. a:x / b:x / c:x / a:y / b:y / c:y
  4. D. a:x / c:x / c:y

Correct answer: A. a:x / c:x / b:y / c:y

Removing a shifts b into index 0 while the loop's index moves to 1, so b is skipped during the first emit. The second emit sees [b, c]. Subjects should iterate over a copy (for h in list(self.subs)).

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic