CS FundamentalsHardProduct-company placement · Python
What does this code print?
What does this code print?
class Count:
def __init__(s, n): s.i = 0; s.n = n
def __iter__(s): return s
def __next__(s):
if s.i >= s.n: raise StopIteration
s.i += 1
return s.i
c = Count(3)
print(list(c), list(c), sum(Count(3)))- A. [1, 2, 3] [1, 2, 3] 6
- B. [0, 1, 2] [] 3
- C. [1, 2, 3] [] 6
- D. [1, 2, 3] [] 0
Correct answer: C. [1, 2, 3] [] 6
__iter__ returns the object itself, so it is an iterator, not a re-iterable collection: the first list() exhausts it and the second finds it already at the end. A fresh Count(3) sums 1 + 2 + 3 = 6. A collection should return a new iterator from __iter__.
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
- In a strictly layered system, 80% of requests pass through the business and service layers unchanged, which merely forward each call to…
- How many of these are Twelve-Factor App recommendations? 1. Write logs as an event stream to stdout and let the environment route them. 2…
- Before refactoring a legacy pricing module with no tests, a developer records its current outputs for many inputs, including results she…
- A new filter must be added to a 400-line untested method. Instead of editing the method's logic, the developer writes the filter as a new…
- A quality-attribute scenario reads: 'During peak sale traffic, a shopper's search request is answered by the catalogue service within 2 s…
- A project planned to finish in month 10 actually finishes in month 13. Why does its schedule performance index (SPI = EV / PV) show 1.0 at…