Open daviddoji opened 3 years ago
Ah, good catch! Yes, my plan was that it would work like the built-in enumerate
, working just like enumerate
does with a single argument, except that the index would start with whatever number you gave. So it should indeed start with 2 and a
, rather than 2 and c
. I'm not sure if it's a mistake in my implementation, or in what I showed.
I'm delighted that you're enjoying the book! If you have a few moments to write a review on Amazon.com (even a short one!), that would be super helpful and appreciated.
This is how I implemented to have such a behavior:
class MyEnumerate_indexed:
def __init__(self, data, start=0):
self.data = data
self.index = start
def __iter__(self):
return MyEnumerateIterator(self.data, self.index)
class MyEnumerateIterator:
def __init__(self, data, start=0):
self.data = data
self.index = start
# to keep track of the index
self.init = start
def __next__(self):
if self.index >= len(self.data) + self.init:
raise StopIteration
value = (self.index, self.data[self.index - self.init])
self.index += 1
return value
Yup, looks good!
Hi @reuven , very nice book, I'm really enjoying doing the "beyond the exercises".
When you asked for writing the "enumerate" class passing an optional argument, did you mean to print return since the optional index or to return everything but with different indexing?
Your solution prints the following:
But I thought you were asking for this (and that's what I coded :)):