reuven / python-workout

Files for the Python Workout book
230 stars 147 forks source link

e46b2 - enumerate with optional argument #15

Open daviddoji opened 3 years ago

daviddoji commented 3 years ago

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
reuven commented 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.

daviddoji commented 3 years ago

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
reuven commented 3 years ago

Yup, looks good!