13.3. Iterator Range

  • Return sequence of numbers

  • It is not a generator

  • Generator (lazy evaluated)

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

  • optional start, inclusive, default: 0

  • required stop, exclusive,

  • optional step, default: 1

>>> from inspect import isgeneratorfunction, isgenerator
>>>
>>>
>>> isgeneratorfunction(range)
False
>>>
>>> result = range(0,5)
>>> isgenerator(result)
False

13.3.1. Example

>>> range(0,3)
range(0, 3)
>>> list(range(0,3))
[0, 1, 2]
>>> tuple(range(0,3))
(0, 1, 2)
>>> set(range(0,3))
{0, 1, 2}
>>> list(range(4,11,2))
[4, 6, 8, 10]

13.3.2. Problem

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

13.3.3. Solution

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

13.3.4. Lazy Evaluation

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

13.3.5. Itertools

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

13.3.6. Assignments

"""
* Assignment: Iterator Range Impl
* Complexity: medium
* Lines of code: 7 lines
* Time: 8 min

English:
    1. Write own implementation of a built-in `range()` function
    2. Define function `myrange` with parameters:
        a. parameter `start: int`
        b. parameter `stop: int`
        c. parameter `step: int`
    3. Don't validate arguments and assume, that user will:
        a. always pass valid type of arguments
        b. never give only one argument
        c. arguments will be unsigned
    4. Do not use built-in function `range()`
    5. Run doctests - all must succeed

Polish:
    1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `range()`
    2. Zdefiniuj funkcję `myrange` z parametrami:
        a. parameter `start: int`
        b. parameter `stop: int`
        c. parameter `step: int`
    3. Nie waliduj argumentów i przyjmij, że użytkownik:
        a. zawsze poda argumenty poprawnych typów
        b. nigdy nie poda tylko jednego argumentu
        c. argumenty będą nieujemne
    4. Nie używaj wbudowanej funkcji `range()`
    5. Uruchom doctesty - wszystkie muszą się powieść

Hint:
    * https://github.com/python/cpython/blob/main/Objects/rangeobject.c

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]
"""

# Write own implementation of a built-in `range()` function
# Define function `myrange` with parameters: `start`, `stop`, `step`
# type: Callable[[int,int,int], list[int]]
def myrange(start=0, stop=None, step=1):
    ...