Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Chained Generators | Advanced Generator Patterns and Applications
Efficient Data Handling in Python

bookChallenge: Chained Generators

In this task, you will deepen your understanding of generator delegation and chaining by implementing two separate generator functions: one that yields a sequence of numbers and another that yields the squares of those numbers. You will then use the yield from statement to chain these generators, producing a single combined sequence that first yields all numbers and then their squares. This exercise builds on your knowledge of generator functions and the use of yield from for delegation, as introduced in the previous chapter.

Opgave

Swipe to start coding

Implement two generator functions: number_generator, which yields numbers from 1 to n, and square_generator, which yields the squares of numbers from 1 to n. Then, implement chained_generator that uses yield from to yield all values from number_generator(n) followed by all values from square_generator(n). The combined sequence should first yield all the numbers, then all their squares.

Løsning

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Suggested prompts:

Can you provide an example of how to implement these generator functions?

How does the `yield from` statement work in this context?

Can you explain the difference between generator delegation and chaining?

close

bookChallenge: Chained Generators

Stryg for at vise menuen

In this task, you will deepen your understanding of generator delegation and chaining by implementing two separate generator functions: one that yields a sequence of numbers and another that yields the squares of those numbers. You will then use the yield from statement to chain these generators, producing a single combined sequence that first yields all numbers and then their squares. This exercise builds on your knowledge of generator functions and the use of yield from for delegation, as introduced in the previous chapter.

Opgave

Swipe to start coding

Implement two generator functions: number_generator, which yields numbers from 1 to n, and square_generator, which yields the squares of numbers from 1 to n. Then, implement chained_generator that uses yield from to yield all values from number_generator(n) followed by all values from square_generator(n). The combined sequence should first yield all the numbers, then all their squares.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3
single

single

some-alt