Editor

Countdown Generator

#217 · Iterators and generators · Beginner · 30 XP · about 4 min

Write a generator countdown(n, step=1) that yields n, then n - step, then n - 2 * step and so on, as long as the number is above 0.

If n is 0 or less, it yields nothing. step is always 1 or more.

Examples

list(countdown(5))        # returns [5, 4, 3, 2, 1]
list(countdown(10, 3))    # returns [10, 7, 4, 1]
list(countdown(0))        # returns []

g = countdown(3)
next(g)                   # returns 3
next(g)                   # returns 2

Note

A generator makes each number only when it is asked for, so countdown(10 ** 18) starts at once, even though the whole countdown would never fit in memory.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.