Вы находитесь на странице: 1из 2

ИПЗ-2020-2

Чепурко Максим Сергеевич


Лабораторная работа №9 Функции
Ф-3
Условие:

Имеется список с множеством вложенностей, у которых также могут быть


вложенности и т.д. Написать функцию, которая "расплющит" список и вернет его
одномерную копию. Также реализовать "расплющивание" до определенной глубины.

def flatten(my_list: list, depth: int = 0) -> list:


"""
Function for "flattening" the list with indication of depth.

Positional arguments:
my_list - list, this is the original input list.
depth - int, depth of "flattening" of the list.

If the depth is greater than 0, the function flattens the list,


if 0 or less, returns it in its original form

Returns:
list - flattened or not according to depth
"""
if depth > 0:
result = []
for elem in my_list:
if isinstance(elem, list):
result += flatten(elem, depth-1)
else:
result += [elem]
return result
else:
return my_list

my_list = eval(input("Введите список: "))


depth = int(input("Введите глубину расплющивания списка: "))
print("Результат: ")
print(flatten(my_list, depth))

Вам также может понравиться