3.5. Star Recap

3.5.1. Assignments

# %% About
# - Name: Star Recap Range
# - Difficulty: medium
# - Lines: 25
# - Minutes: 13

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Write own implementation of a built-in function `range()`,
#    example usage: `myrange(10)`, `myrange(0, 10)` or `myrange(0, 10, 2)`
# 2. Note, that function does not take any keyword arguments
# 3. How to implement passing only stop argument, i.e. `myrange(10)`?
# 4. Use length check of `*args` and `**kwargs`
# 5. Error messages must be consistent with built-in function `range()`:
#    - myrange() -> `TypeError: range expected at least 1 argument, got 0`
#    - myrange(1,2,3,4) -> `TypeError: range expected at most 3 arguments, got 4`
#    - myrange(stop=2) -> `TypeError: range() takes no keyword arguments`
#    - myrange(start=1, stop=2) -> `TypeError: range() takes no keyword arguments`
#    - myrange(start=1, stop=2, step=2) -> `TypeError: range() takes no keyword arguments`
# 6. Run doctests - all must succeed

# %% Polish
# 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `range()`,
#    przykład użycia: `myrange(10)`, `myrange(0, 10)` lub `myrange(0, 10, 2)`
# 2. Zauważ, że funkcja nie przyjmuje żadnych argumentów nazwanych (keyword)
# 3. Jak zaimplementować możliwość podawania tylko końca, tj. `myrange(10)`?
# 4. Użyj sprawdzania długości `*args` i `**kwargs`
# 5. Komunikaty błędów muszą być zgodne z wbudowaną funkcją `range()`:
#    - myrange() -> `TypeError: range expected at least 1 argument, got 0`
#    - myrange(1,2,3,4) -> `TypeError: range expected at most 3 arguments, got 4`
#    - myrange(stop=2) -> `TypeError: range() takes no keyword arguments`
#    - myrange(start=1, stop=2) -> `TypeError: range() takes no keyword arguments`
#    - myrange(start=1, stop=2, step=2) -> `TypeError: range() takes no keyword arguments`
# 6. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - https://github.com/python/cpython/blob/main/Objects/rangeobject.c#LC75
# - `raise TypeError('error message')`
# - `if len(args) == ...`

# %% Example
# >>> myrange(0, 10, 2)
# [0, 2, 4, 6, 8]
#
# >>> myrange(0, 5)
# [0, 1, 2, 3, 4]
#
# >>> myrange(5)
# [0, 1, 2, 3, 4]
#
# >>> myrange()
# Traceback (most recent call last):
# TypeError: myrange expected at least 1 argument, got 0
#
# >>> myrange(1,2,3,4)
# Traceback (most recent call last):
# TypeError: myrange expected at most 3 arguments, got 4
#
# >>> myrange(stop=2)
# Traceback (most recent call last):
# TypeError: myrange() takes no keyword arguments
#
# >>> myrange(start=1, stop=2)
# Traceback (most recent call last):
# TypeError: myrange() takes no keyword arguments
#
# >>> myrange(start=1, stop=2, step=2)
# Traceback (most recent call last):
# TypeError: myrange() takes no keyword arguments

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction
>>> assert isfunction(myrange)

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

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

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

>>> myrange()
Traceback (most recent call last):
TypeError: myrange expected at least 1 argument, got 0

>>> myrange(1,2,3,4)
Traceback (most recent call last):
TypeError: myrange expected at most 3 arguments, got 4

>>> myrange(1,2,3,4,5)
Traceback (most recent call last):
TypeError: myrange expected at most 3 arguments, got 5

>>> myrange(stop=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments

>>> myrange(start=1, stop=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments

>>> myrange(start=1, stop=2, step=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
myrange: Callable[[int,int,int], list[int]]

# %% Data

# %% Result
def myrange(*args, **kwargs):
    if kwargs:
        raise TypeError('myrange() takes no keyword arguments')

    current = start
    result = []
    while current < stop:
        result.append(current)
        current += step
    return result

# %% About
# - Name: Star Recap Define
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Create function `mean()`, which calculates arithmetic mean
# 2. If there is no arguments, raise ValueError with message:
#    'At least one argument is required'
# 3. Function can have arbitrary number of positional arguments
# 4. Non-functional requirements:
#    - Do not import any libraries and modules
#    - Use builtin functions `sum()` and `len()`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Napisz funkcję `mean()`, wyliczającą średnią arytmetyczną
# 2. Jeżeli nie podano argumentów, podnieś wyjątek ValueError z wiadomością:
#    'At least one argument is required'
# 3. Funkcja przyjmuje dowolną liczbę pozycyjnych argumentów
# 4. Wymagania niefunkcjonalne:
#    - Nie importuj żadnych bibliotek i modułów
#    - Użyj wbudowanych funkcji `sum()` i `len()`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `raise ValueError('error message')`
# - `sum(...) / len(...)`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> mean(1)
1.0
>>> mean(1, 2)
1.5
>>> mean(1, 2, 3)
2.0
>>> mean(1, 2, 3, 4)
2.5
>>> mean()
Traceback (most recent call last):
ValueError: At least one argument is required
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
mean: Callable[[tuple[int|float]], float|Exception]

# %% Data

# %% Result
def mean():
    ...

# %% About
# - Name: Star Recap Define
# - Difficulty: easy
# - Lines: 3
# - Minutes: 8

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define `result: list[dict]`
# 2. Iterate over `DATA` separating `values` from `species`
# 3. To `result` append dict with:
#    - key: `species`, value: species name
#    - key: `mean`, value: arithmetic mean of `values`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[dict]`
# 2. Iteruj po `DATA` separując `values` od `species`
# 3. Do `result` dodawaj dict z:
#    - klucz: `species`, wartość: nazwa gatunku
#    - klucz: `mean`, wartość: wynik średniej arytmetycznej `values`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# [{'species': 'virginica', 'mean': 3.875},
#  {'species': 'setosa', 'mean': 2.65},
#  {'species': 'versicolor', 'mean': 3.475},
#  {'species': 'virginica', 'mean': 6.0},
#  {'species': 'versicolor', 'mean': 3.95},
#  {'species': 'setosa', 'mean': 4.7}]

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert type(result) is list, \
'Result must be a list'

>>> assert all(type(row) is dict for row in result), \
'All elements in result must be a dict'

>>> result  # doctest: +NORMALIZE_WHITESPACE
[{'species': 'virginica', 'mean': 3.875},
 {'species': 'setosa', 'mean': 2.65},
 {'species': 'versicolor', 'mean': 3.475},
 {'species': 'virginica', 'mean': 6.0},
 {'species': 'versicolor', 'mean': 3.95},
 {'species': 'setosa', 'mean': 4.7}]
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports

# %% Types
result: list[dict]

# %% Data
DATA = [
    ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
    (5.8, 2.7, 5.1, 1.9, 'virginica'),
    (5.1, 0.2, 'setosa'),
    (5.7, 2.8, 4.1, 1.3, 'versicolor'),
    (6.3, 5.7, 'virginica'),
    (6.4, 1.5, 'versicolor'),
    (4.7, 'setosa'),
]


def mean(*args):
    return sum(args) / len(args)

# %% Result
result = ...

# %% About
# - Name: Star Recap Args
# - Difficulty: easy
# - Lines: 6
# - Minutes: 8

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Modify function `isnumeric()`
# 2. Function should take arbitrary number of positional arguments
# 3. If there is no arguments, raise TypeError with message:
#    'At least one argument is required'
# 4. Given arguments can be of any type,
#    example: int, float, bool, None, tuple, list, set, dict
# 5. Return `True` if all arguments are numeric only,
#    example: `int`, `float`
# 6. Return `False` if any argument is different type
# 7. Compare using `type()` and `isinstance()`
# 8. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `isnumeric()`
# 2. Funkcja powinna przyjmować dowolną liczbę argumentów pozycyjnych
# 3. Jeżeli nie podano argumentów, podnieś wyjątek TypeError z wiadomością:
#    'At least one argument is required'
# 4. Podawane argumenty mogą być dowolnego typu,
#    przykład: int, float, bool, None, tuple, list, set, dict
# 5. Zwróć `True` jeżeli wszystkie argumenty są tylko numeryczne
#    przykład: `int`, `float`
# 6. Zwróć `False` jeżeli którykolwiek argument jest innego typu
# 7. Porównaj użycie `type()` i `isinstance()`
# 8. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `isinstance(obj, type1|type2)`
# - `type(obj)`
# - `... in tuple()`
# - `raise TypeError('error message')`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction
>>> assert isfunction(isnumeric), \
'isnumeric must be a function'

>>> isnumeric()
Traceback (most recent call last):
TypeError: At least one argument is required

>>> isnumeric(1)
True
>>> isnumeric(1.0)
True
>>> isnumeric('one')
False
>>> isnumeric(True)
False

>>> isnumeric(1, 1.0)
True
>>> isnumeric(1,  1.0, 'one')
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
isnumeric: Callable[[tuple[int|float]], bool|Exception]

# %% Data

# %% Result
def isnumeric(*args):
    ...

# %% About
# - Name: Star Recap Kwargs
# - Difficulty: medium
# - Lines: 7
# - Minutes: 8

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 0. Mind, this assignment is very similar to the previous one,
#    but not identical
# 1. Modify function `isnumeric()`
# 2. Function should take arbitrary number of positional or keyword arguments
# 3. If there is no arguments, raise TypeError with message:
#    'At least one argument is required'
# 4. Given arguments can be of any type,
#    example: int, float, bool, None, tuple, list, set, dict
# 5. Return `True` if all arguments are numeric only
#    that is: `int` or `float`
# 6. Return `False` if any argument is different type
# 7. Compare using `type()` and `isinstance()`
# 8. Run doctests - all must succeed

# %% Polish
# 0. Zwróć uwagę, że to zadanie jest bardzo podobne do poprzedniego,
#    ale to nie jest identyczne
# 1. Zmodyfikuj funkcję `isnumeric()`
# 2. Funkcja powinna przyjmować dowolną liczbę argumentów pozycyjnych i nazwanych (keyword)
# 3. Jeżeli nie podano argumentów, podnieś wyjątek TypeError z wiadomością:
#    'At least one argument is required'
# 4. Podawane argumenty mogą być dowolnego typu,
#    przykład: int, float, bool, None, tuple, list, set, dict
# 5. Zwróć `True` jeżeli wszystkie argumenty są tylko numeryczne
#    to jest: `int` lub `float`
# 6. Zwróć `False` jeżeli którykolwiek argument jest innego typu
# 7. Porównaj użycie `type()` i `isinstance()`
# 8. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `isinstance(obj, type1|type2)`
# - `type(obj)`
# - `dict.values()`
# - `tuple() += tuple()`
# - `raise TypeError('error message')`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction
>>> assert isfunction(isnumeric), \
'isnumeric must be a function'

>>> isnumeric()
Traceback (most recent call last):
TypeError: At least one argument is required

>>> isnumeric(1)
True
>>> isnumeric(1.0)
True
>>> isnumeric('one')
False
>>> isnumeric(True)
False

>>> isnumeric(1, 1.0)
True
>>> isnumeric(1,  1.0, 'one')
False

>>> isnumeric(a=1)
True
>>> isnumeric(a=1.0)
True
>>> isnumeric(a='one')
False
>>> isnumeric(a=True)
False

>>> isnumeric(a=1, b=1.0)
True
>>> isnumeric(a=1,  b=1.0, c='one')
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
isnumeric: Callable[[tuple[int|float], dict[str,int|float]], bool|Exception]

# %% Data

# %% Result
def isnumeric(*args, **kwargs):
    ...