add solution without recursion

This commit is contained in:
Dmitry Afanasyev 2022-04-16 14:46:01 +03:00
parent 8a23510095
commit c8780af4f6

View File

@ -12,7 +12,7 @@
Пример: Пример:
""" """
import json import json
from typing import Any, List, Tuple from typing import Any, List, Tuple, Union, Dict
forest = {'b': 1, forest = {'b': 1,
'c': {'d': 2, 'c': {'d': 2,
@ -30,11 +30,22 @@ forest = {'b': 1,
}, },
}, },
}, },
'a': 11,
'u': {'w': {'z': {'y': 42,
'x': 100,
},
'f': 12,
'b': 15,
},
'q': 90,
}
} }
# Переводим в такой вид: # Переводим в такой вид:
result = [('b', 1), ('c.d', 2), ('c.f', 3), ('e.i', 4), ('e.j.k', 5), ('e.j.l', 6), ('m.n', 7), result = [('a', 11), ('b', 1), ('c.d', 2), ('c.f', 3), ('e.i', 4), ('e.j.k', 5), ('e.j.l', 6), ('m.n', 7), ('m.o.p', 8),
('m.o.p', 8), ('m.o.r.s', 9), ('m.o.r.t', 10), ] ('m.o.r.s', 9), ('m.o.r.t', 10), ('u.q', 90), ('u.w.b', 15), ('u.w.f', 12), ('u.w.z.x', 100), ('u.w.z.y', 42),
]
def dict_to_list(sub_tree: dict, current_name: str, items_list: List[tuple]) -> List[tuple]: def dict_to_list(sub_tree: dict, current_name: str, items_list: List[tuple]) -> List[tuple]:
@ -48,13 +59,13 @@ def dict_to_list(sub_tree: dict, current_name: str, items_list: List[tuple]) ->
res = dict_to_list(forest, '', []) res = dict_to_list(forest, '', [])
print(res) print(sorted(res))
# Reverse task: # Reverse task:
def list_to_dict(data: List[Tuple['str', int]]) -> dict: def list_to_dict(data: List[Tuple[str, int]]) -> dict:
tree = {} tree = {}
for item in data: for item in data:
curr_tree = tree curr_tree = tree
@ -70,3 +81,33 @@ def list_to_dict(data: List[Tuple['str', int]]) -> dict:
parsed = json.dumps(list_to_dict(result), indent=4) parsed = json.dumps(list_to_dict(result), indent=4)
print(parsed) print(parsed)
# without recursion
def dict_to_list_without_recursion(data: Dict[str, Union[int, dict]]) -> List[Tuple[str, Union[int, dict]]]:
result_list = []
temp_lst = []
count = 0
for key, value in data.items():
if isinstance(value, dict):
count += 1
temp_lst.append((key, value))
for _ in range(count):
for item in temp_lst:
if isinstance(item[1], dict):
temp_lst.remove(item)
for sub_key, sub_value in item[1].items():
temp_lst.append((f'{item[0]}.{sub_key}', sub_value))
else:
if item not in result_list:
result_list.append(item)
del temp_lst
return result_list
res_lst = dict_to_list_without_recursion(forest)
print(sorted(res_lst))