CS FundamentalsVery hardProduct-company placement · Python interview
Python generators implement the Iterator pattern lazily. What does this code print (lines joined by ' / ')?
Python generators implement the Iterator pattern lazily. What does this code print (lines joined by ' / ')?
def countdown(n):
print("start")
while n > 0:
yield n
n -= 1
print("end")
g = countdown(3)
print("made")
print(next(g), next(g))
print(list(g))- A. start / made / 3 2 / [1] / end
- B. made / start / 3 2 / end / [1]
- C. made / start / 3 2 / [1] / end
- D. start / made / 3 2 / end / [1]
Correct answer: B. made / start / 3 2 / end / [1]
Calling countdown(3) runs no code, so 'made' comes first; the first next() prints 'start' and yields 3, then 2. list(g) yields 1, prints 'end' when the loop finishes, and only then is [1] printed.
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
- What does this code print (lines joined by ' / ')? python class Guard: def enter(self): print("enter") return self def exit(self, exctype…
- Mixins rely on Python's method resolution order. What does this print? python class Base: def save(self): return ["Base"] class Log(Base)…
- This code illustrates the 'fragile base class' problem. What does it print? python class Bag: def init(self): self.items = [] def…
- What does this code print? python from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ... def…
- Under design by contract, a method sqrt(x) has the precondition x ≥ 0. A caller passes -4 and the method fails. Whose bug is it, and which…
- A service catches every exception in a broad try/except, logs nothing and returns an empty list, so a database outage looks like 'no…