Пример 1. Сумма чисел списка
def recursive_sum(numbers: list) -> float:
"""Return the sum of all numbers in a list recursively."""
if not isinstance(numbers, list):
raise TypeError("Argument must be a list")
if not numbers:
return 0
head = numbers[0]
if not isinstance(head, (int, float)):
raise TypeError(f"All elements must be numbers, got {type(head).__name__}")
return head + recursive_sum(numbers[1:])
numbers = [1, 2, 3, 4, 5]
try:
print(recursive_sum(numbers))
except (TypeError, ValueError) as e:
print(f"Ошибка: {e}")
Пример 2. Реверс строки
def reverse_string(text: str) -> str:
"""Return the reversed string using recursion."""
if not isinstance(text, str):
raise TypeError("Argument must be a string")
if len(text) <= 1:
return text
return text[-1] + reverse_string(text[:-1])
text = "recursion"
try:
print(reverse_string(text))
except TypeError as e:
print(f"Ошибка: {e}")
Пример 3. Глубина вложенности списка
def list_depth(nested_list: list) -> int:
"""Return the maximum nesting depth of a list."""
if not isinstance(nested_list, list):
raise TypeError("Argument must be a list")
max_inner = 0
for item in nested_list:
if isinstance(item, list):
max_inner = max(max_inner, list_depth(item))
return 1 + max_inner
nested_list = [1, [2, [3, [4, [5]]]], 6, [[7, 8], 9]]
try:
print("Максимальная глубина:", list_depth(nested_list))
except TypeError as e:
print(f"Ошибка: {e}")
Пример 4. Сумма продаж по дереву отделов
def total_sales(department: dict) -> int | float:
"""Return the total sales of a department and all its sub-departments."""
if not isinstance(department, dict):
raise TypeError("Department must be a dict")
sales = department.get("sales", 0)
total = sales
sub_departments = department.get("sub_departments")
if sub_departments is not None:
if not isinstance(sub_departments, list):
raise TypeError("sub_departments must be a list")
for sub in sub_departments:
if not isinstance(sub, dict):
raise TypeError("Each sub_department must be a dict")
total += total_sales(sub)
return total
company_structure = {
"dept_name": "Head Office",
"sales": 100,
"sub_departments": [
{
"dept_name": "Sales Department",
"sales": 200,
"sub_departments": [
{"dept_name": "B2B Sales", "sales": 120}
]
},
{
"dept_name": "IT Department",
"sales": 150,
"sub_departments": [
{
"dept_name": "DevOps",
"sales": 300,
"sub_departments": [
{"dept_name": "Cloud Infrastructure", "sales": 180}
]
},
{"dept_name": "QA Department", "sales": 90}
]
}
]
}
try:
print("Общая сумма продаж:", total_sales(company_structure))
except TypeError as e:
print(f"Ошибка: {e}")
Пример 5. Читабельный формат словаря
def flatten_dict(data: dict, prefix: str = "") -> dict:
"""Convert a nested dict into a flat dict with dot-separated keys."""
if not isinstance(data, dict):
raise TypeError("Argument must be a dict")
result = {}
for key, value in data.items():
full_key = f"{prefix}.{key}" if prefix else key
if isinstance(value, dict):
result.update(flatten_dict(value, full_key))
else:
result[full_key] = value
return result
data = {
"user": {
"id": 123,
"info": {
"name": "Alice",
"location": {
"city": "Berlin",
"coordinates": {"lat": 52.52, "lon": 13.405}
},
"hobby": ["swimming", "drawing"]
}
},
"score": 95
}
flat = flatten_dict(data)
print("Данные для анализа:")
for key, value in flat.items():
print(f"{key} : {value}")
Как запустить в VS Code
- Создайте файл, например
practice_12.py.
- Скопируйте код одного из примеров выше.
- Откройте терминал в VS Code (Ctrl + `).
- Убедитесь, что активировано виртуальное окружение:
venv\Scripts\activate (Windows) или source venv/bin/activate (Mac/Linux).
- Запустите:
python practice_12.py