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': 'c1', 'id': 'c22', 'type': 'category', 'name': 'cat22'},
- {'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': 'c1', 'id': 'o11', 'type': 'offer', 'name': 'of11',
- 'price': 11},
- {'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,
- 'price': 0,
- 'children': []
- }
- # --- до сюда то что можем +- незапарно получить из базы ---
- def smart_map(iterator):
- """
- map, который возвращает цену товара и
- параллельно считает количество товаров
- :param iterator: offers
- :return:
- """
- global n
- for n, val in enumerate(iterator, start=1):
- yield val.get('price', 0)
- children = {} # {parent_id: [child1, child2]}
- n = 0
- for i in range(len(categories) - 1, -1, -1):
- pre_res = {'children': [], 'price': 0}
- # Записываем саму категорию
- pre_res.update(categories[i])
- curr_id = pre_res['id']
- parent_id = pre_res['parent_id']
- # Товаы, которые принадлежат нашей категории
- offers_parents = filter(lambda x: x['parent_id'] == curr_id,
- offers2categories)
- # Считаем сумму товаров и паралельно их количество
- s = sum(smart_map(offers_parents))
- # Высчитываем среднюю цену товаров
- pre_res['price'] = s // n
- # Суммируем средние цены вложенных категорий и срденюю ценюу товаров
- if curr_id in children:
- old_n = n
- pre_res['price'] += sum(smart_map(children.get(curr_id, [])))
- pre_res['price'] //= n + old_n
- # Добавляем товары категории
- pre_res['children'].extend(filter(lambda x: x['parent_id'] == curr_id,
- offers2categories))
- # Добавляем вложенные категории
- pre_res['children'].extend(children.get(curr_id, []))
- if parent_id not in children:
- children[parent_id] = [pre_res.copy()]
- else:
- children[parent_id].append(pre_res.copy())
- # Товаы, которые принадлежат нашей категории
- offers_parents = filter(lambda x: x['parent_id'] == result['id'],
- offers2categories)
- # Считаем сумму товаров и паралельно их количество
- s = sum(smart_map(offers_parents))
- # Высчитываем среднюю цену товаров
- result['price'] = s // n
- old_n = n
- result['price'] += sum(smart_map(children.get(result['id'], [])))
- result['price'] //= n + old_n
- # Добавляем товары категории
- result['children'].extend(filter(lambda x: x['parent_id'] == result['id'],
- offers2categories))
- # Добавляем вложенные категории
- result['children'].extend(children[result['id']])
- pprint.pprint(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement