python-workout icon indicating copy to clipboard operation
python-workout copied to clipboard

e46b2 - enumerate with optional argument

Open daviddoji opened this issue 4 years ago • 3 comments

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:

** Starting at 0 **
0: a
1: b
2: c
** Starting at 2 **
2: c

But I thought you were asking for this (and that's what I coded :)):

** Starting at 0 **
0: a
1: b
2: c
** Starting at 2 **
2: a
3: b
4: c

daviddoji avatar Aug 21 '21 13:08 daviddoji

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.

reuven avatar Aug 23 '21 07:08 reuven

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

daviddoji avatar Aug 23 '21 08:08 daviddoji

Yup, looks good!

reuven avatar Aug 23 '21 08:08 reuven