CS FundamentalsVery hardProduct-company placement · Python interview
This Observer code registers three listeners. What does it print?
This Observer code registers three listeners. What does it print?
class Subject:
def __init__(self): self.obs = []
def attach(self, f): self.obs.append(f)
def notify(self, v):
for f in self.obs: f(v)
log = []
s = Subject()
for k in range(3):
s.attach(lambda v: log.append(v * k))
s.notify(10)
print(log)- A. [0, 10, 20]
- B. [20]
- C. [20, 20, 20]
- D. [0, 0, 0]
Correct answer: C. [20, 20, 20]
All three lambdas close over the same variable k, looked up when they run; by then the loop has finished with k = 2, so each appends 10 x 2. Binding the value (lambda v, k=k: ...) would give [0, 10, 20].
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- A drawing app has 4 shape types and must render each through 3 back-ends (SVG, Canvas, PDF). Building one subclass per combination needs…
- A compiler has a stable set of AST node classes (Number, BinaryOp, Call, Variable) but keeps adding new operations: type-check…
- A file-manager must compute the total size of a folder, where a folder may contain files and other folders, and client code should call…
- A text editor needs multi-level undo and redo, and also wants to queue and log user actions such as 'insert text' or 'delete line'. Which…
- A vending machine's behaviour for insertCoin() and selectItem() differs completely in the states Idle, HasCoin, Dispensing and SoldOut…
- A report class defines generate() as: fetchData(); format(); export(). Subclasses PdfReport and CsvReport override only format() and…