Challenge: 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.
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.
Ratkaisu
Kiitos palautteestasi!
single
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Awesome!
Completion rate improved to 6.67
Challenge: Chained Generators
Pyyhkäise näyttääksesi valikon
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.
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.
Ratkaisu
Kiitos palautteestasi!
single