Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pprint
- # --- Предполагаемые выходные данные ---
- categories = [
- {'parent_id': 'c1', 'id': 'c2', 'type': 'category', 'name': 'cat2'},
- {'parent_id': 'c2', 'id': 'c3', 'type': 'category', 'name': 'cat3'},
- {'parent_id': 'c3', 'id': 'c4', 'type': 'category', 'name': 'cat4'},
- ]
- offers2categories = [
- {'parent_id': 'c1', 'id': 'o1', 'type': 'offer', 'name': 'of1',
- 'price': 1},
- {'parent_id': 'c2', 'id': 'o2', 'type': 'offer', 'name': 'of2',
- 'price': 2},
- {'parent_id': 'c3', 'id': 'o3', 'type': 'offer', 'name': 'of3',
- 'price': 3},
- {'parent_id': 'c4', 'id': 'o4', 'type': 'offer', 'name': 'of4',
- 'price': 4},
- ]
- result = {
- 'id': 'c1',
- 'name': 'cat1',
- 'parent_id': None,
- # Цену общую посчитать в целом не сложно
- # (можно ее вообще в саомм конце только записать,
- # если использовать мое решение)
- # sum(map(
- # lambda x: x['price'], offers2categories)) // len(offers2categories)
- 'price': 0,
- 'children': []
- }
- # --- до сюда то что можем +- незапарно получить из базы ---
- def smart_map(iterator):
- """
- map, который возвращает цену товара и
- параллельно считает количество товаров
- :param iterator: offers
- :return:
- """
- global n
- for n, val in enumerate(iterator, start=1):
- yield val['price']
- pre_res_copy = {}
- prev_sum = prev_count = 0
- n = 0
- for i in range(len(categories) - 1, -1, -1):
- curr_id = categories[i]['id']
- pre_res = {'children': [], 'price': 0}
- # Записываем саму категорию
- pre_res.update(categories[i])
- # Товаы, которые принадлежат нашей категории
- offers_parents = filter(lambda x: x['parent_id'] == curr_id,
- offers2categories)
- # Считаем сумму товаров и паралельно их количество
- s = sum(smart_map(offers_parents))
- # Высчитываем среднюю цену
- pre_res['price'] = (s + prev_sum) // (n + prev_count)
- if pre_res_copy:
- # Добавляем вложенную категорию
- pre_res['children'].append(pre_res_copy.copy())
- # Добавляем товары категории
- pre_res['children'].extend(filter(lambda x: x['parent_id'] == curr_id,
- offers2categories))
- # Сохраняем, чтобы впоследствии использовать как вложенную
- pre_res_copy = pre_res.copy()
- # Обновляем счетчики общего числа товаров и суммы
- prev_count += n
- prev_sum += s
- # Добавляем товары, которые непосредствнно принадлежат основной категории
- offers_parents = filter(lambda x: x['parent_id'] == curr_id, offers2categories)
- # Считаем сумму товаров и паралельно их количество
- s = sum(smart_map(offers_parents))
- result['price'] = (s + prev_sum) // (n + prev_count)
- result['children'].extend(filter(lambda x: x['parent_id'] == result['id'],
- offers2categories))
- # Добавляем вложенность
- result['children'].append(pre_res_copy)
- pprint.pprint(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement