3.2. Idiom Range

  • Return sequence of numbers

  • It is not a generator

  • Generator (lazy evaluated)

  • Built-in

3.2.1. Syntax

  • range([start], <stop>, [step])

  • optional start, inclusive, default: 0

  • required stop, exclusive,

  • optional step, default: 1

3.2.2. Problem

>>> i = 0
>>> result = []
>>>
>>> while i < 3:
...     result.append(i)
...     i += 1
>>>
>>> result
[0, 1, 2]

3.2.3. Solution

>>> result = range(0,3)
>>>
>>> list(result)
[0, 1, 2]

3.2.4. Lazy Evaluation

>>> for i in range(0,3):
...     print(i)
0
1
2

3.2.5. Itertools

>>> from itertools import count
>>>
>>>
>>> result = count(3, 2)
>>>
>>> next(result)
3
>>> next(result)
5
>>> next(result)
7

3.2.6. Assignments

Code 3.43. Solution
"""
* Assignment: Idioms Range Impl
* Complexity: medium
* Lines of code: 7 lines
* Time: 13 min

English:
    1. Define function `myrange` with parameters: `start`, `stop`, `step`
    2. Write own implementation of a built-in `range()` function
    3. Don't validate arguments and assume, that user will:
        a. never give only one argument; always it will be either two or three arguments
        b. never give keyword arguments; always it will be positional arguments
        c. never give more than three arguments
    4. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `myrange` z parametrami: `start`, `stop`, `step`
    2. Zaimplementuj własne rozwiązanie wbudowanej funkcji `range()`
    3. Nie waliduj argumentów i przyjmij, że użytkownik:
        a. nigdy nie poda tylko jednego argumentu; zawsze będą to dwa lub trzy argumenty
        b. nigdy nie poda argumentów keywordowych; zawsze będą to argumenty pozycyjne
        c. nigdy nie poda więcej niż trzy argumenty
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert isfunction(myrange)

    >>> myrange(0, 10, 2)
    [0, 2, 4, 6, 8]

    >>> myrange(0, 5)
    [0, 1, 2, 3, 4]
"""