Problem 361870 · easy · Level 03 Linear Management & Searching

Waiting Longer After Each Failure

py-generators · yield · infinite sequences

A phone app that loses its connection tries again, and waits longer after each failed attempt so it does not flood the server: first start seconds, then factor times as long, then factor times that, and so on. No wait is ever longer than cap seconds; once the waits reach the cap they stay there.

Nobody knows in advance how many attempts will be needed, so write retry_delays(start, factor, cap) as a generator of the waits that never runs out: the caller takes as many as it needs.

The tests take the first n waits with the helper first(gen, n), which is available with Run (it refuses a list, so return a generator).

Examples

Input:  first(retry_delays(1, 2, 30), 8)
Output: [1, 2, 4, 8, 16, 30, 30, 30]
Explanation: 32 would exceed the cap of 30.

Input:  first(retry_delays(0.5, 3, 10), 4)
Output: [0.5, 1.5, 4.5, 10]

Constraints

  • 0 < start, 1 <= factor, 0 < cap; the numbers may be integers or floats.
  • If start is already above cap, every wait is cap.
  • The tests may take up to 10**5 waits.

Goals

  • Write a generator function with `yield`
  • Produce an endless sequence that the caller cuts off
  • Keep the generator's state in ordinary local variables between yields
Starting Python…