LearnFrenzy
Sign in Take a free test

Iterators and Generators · Exercise 4 of 4

Iterators and Generators Iterators and Generators Coding Problems

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Python programs built with custom iterators, generator functions, yield from and itertools. Write each one yourself first, then open the solution – every solution was run on Python 3, the output shown is the real output, and Run opens it in the online Python compiler.

Question 1 Medium

Write a FloatRange iterable (start, stop, step) that works with decimal steps, can be looped over more than once, and avoids accumulating floating-point error.

Question page & discussion
Question 2 Easy

Write a generator that yields Fibonacci numbers below a limit, and use it to print the series below 100 and the count of even terms below 4,000,000.

Question page & discussion
Question 3 Medium

Write a generator that reads a CSV file row by row and yields dicts, then compute totals without loading the whole file.

Question page & discussion
Question 4 Medium

Write batches(iterable, size) that yields lists of up to size items from any iterable (including a generator), and use it to "upload" 11 records in batches of 4.

Question page & discussion
Question 5 Hard

Write an infinite generator of prime numbers and use islice and takewhile to print the first 15 primes and the primes between 100 and 150.

Question page & discussion
Question 6 Medium

Build a pipeline of generator functions that strips raw text lines, skips blanks and comments, converts to numbers (skipping bad ones) and keeps values in a valid range.

Question page & discussion
Question 7 Medium

Write a generator that flattens nested lists and tuples to any depth (but keeps strings whole), and count the leaves.

Question page & discussion
Question 8 Hard

Write a generator that receives readings with send() and yields the running average and the maximum so far; feed it a list of temperatures.

Question page & discussion
Question 9 Medium

Write a generator that yields each window of k consecutive items from any iterable (using a deque), and print the 3-day moving averages of daily sales.

Question page & discussion
Question 10 Hard

Write a round_robin(*iterables) generator that takes one item from each iterable in turn, dropping iterables as they run out, to interleave task queues.

Question page & discussion
All exercises doneBack to Iterators and GeneratorsRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links