Doubt: Function of generators

Asked

Viewed 67 times

3

Write your own generator function which works as the internal enumerate function. Using the function thus:

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 the 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 really hard time on this subject(Generators), I can’t understand how I can solve this problem , I believe I should use the function enumerate() , 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))
  • You can include which error is preventing you from succeeding with the code?

  • @Williamlio actually I’m not even able to think how I should create this code , I repeat , because I don’t understand the subject related to generators .

  • When I first read it, I understood something very different, when I reread it. I found it very interesting. I’ll keep an eye out, I also want to know the answer ;)

  • @Barbetta , me too, I’m not in any way able to find or come up with a code to solve this.

1 answer

5


You don’t need to know the background of generators to make a replica of enumerate, because this is simple. Its implementation would be 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 element of the eternal.

See the example working on Ideone

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.