Bird
0
0

Identify the error in this iterator implementation snippet:

medium📝 Analysis Q6 of 15
LLD - Behavioral Design Patterns — Part 1

Identify the error in this iterator implementation snippet:

class MyIterator:
def __init__(self, collection):
self.collection = collection
def hasNext(self):
return self.index < len(self.collection)
def next(self):
if self.hasNext():
element = self.collection[self.index]
self.index += 1
return element
else:
raise StopIteration()

What is missing that causes a runtime error?

AInitialization of self.index in constructor
BReturn statement in next() method
CDefinition of hasNext() method
DRaising StopIteration exception
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor for index initialization

    The constructor does not initialize self.index, so it is undefined when used.
  2. Step 2: Identify impact of missing initialization

    Using self.index without initialization causes runtime error.
  3. Final Answer:

    Initialization of self.index in constructor -> Option A
  4. Quick Check:

    Missing self.index init causes error [OK]
Quick Trick: Always initialize iterator position variable before use [OK]
Common Mistakes:
MISTAKES
  • Assuming next() lacks return
  • Thinking hasNext() is undefined

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes