I had an assignment for my programming class to write a generator function that takes an int ( n
) and a generator ( gen
) as arguments and generates the first n
elements of the given generator. I wrote:
from typing import Iterator, Any
def basic_generator(n): # Just a generator function to be able to test it out
while True:
yield n
n += 1
def tryout(n: int, gen: Iterator[Any]) -> Iterator[Any]:
i = 0
while i < n:
next(gen)
yield i
i = i + 1
In the feedback I received it told me it's wrong but it didn't say why. I get that it doesn't work but I don't understand why. Could someone please explain it to me?
You are yield
ing the counter instead of the value ... Change to yield next(gen)
.
It would also be cleaner to use a for
loop instead of a while
:
def tryout(n: int, gen: Iterator[Any]) -> Iterator[Any]:
for _ in range(n):
yield next(gen)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.