Doubt: Function of generators

3

Write your own generator function that functions as the internal enumerate function. Using the function like this:

lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]

for i, lesson in my_enumerate(lessons, 1):
    print("Lesson {}: {}".format(i, lesson))

should result in exit:

Lesson 1: Why Python Programming
Lesson 2: Data Types and Operators
Lesson 3: Control Flow
Lesson 4: Functions
Lesson 5: Scripting

"So, guys, I'm having a lot of trouble on this subject (generators), I can not figure out how to solve this problem, I think I should use the enumerate () function but my lack of understanding of the subject is compromising my attempts. "

lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]

def my_enumerate(iterable, start=0):
    # Implement your generator function here


for i, lesson in my_enumerate(lessons, 1):
    print("Lesson {}: {}".format(i, lesson))
    
asked by anonymous 19.04.2018 / 03:55

1 answer

5

You do not need to know in depth about generators to make a replica of enumerate , as this is simple. Your implementation would look something like:

def my_enumerate(iterable, start=0):
    current = start  # começa no numero passado como segundo parametro
    for elem in iterable: 
        yield current, elem  # gera uma nova tupla
        current += 1  # aumenta o numero corrente

The yield is responsible for generating each tuple with the position and the iterable element.

See the example working on Ideone

This is a topic that you should follow with some calmness and preference when you have mastered the basics of Python, as it is more complicated, and still has a lot of details.

    
19.04.2018 / 04:32