Forward and reverse `range` [ref]
Problem
- Generate integers from
0 through 4 and from 2 through 5.
- Generate even integers from
0 through 8.
- Generate integers from
5 down through 1.
- Generate reverse indices for a list of length
4.
- Generate starting positions for a length-
3 substring in a length-5 string.
Python solution
list(range(5)) # [0, 1, 2, 3, 4]
list(range(2, 6)) # [2, 3, 4, 5]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]
n = 4
list(range(n - 1, -1, -1)) # [3, 2, 1, 0]
n, k = 5, 3
list(range(n - k + 1)) # [0, 1, 2]
Links