Advertisement
gg-master

Untitled

Jun 17th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. import pprint
  2.  
  3. # --- Предполагаемые выходные данные ---
  4. categories = [
  5. {'parent_id': 'c1', 'id': 'c2', 'type': 'category', 'name': 'cat2'},
  6. {'parent_id': 'c1', 'id': 'c22', 'type': 'category', 'name': 'cat22'},
  7. {'parent_id': 'c2', 'id': 'c3', 'type': 'category', 'name': 'cat3'},
  8. {'parent_id': 'c3', 'id': 'c4', 'type': 'category', 'name': 'cat4'},
  9. ]
  10.  
  11. offers2categories = [
  12. {'parent_id': 'c1', 'id': 'o1', 'type': 'offer', 'name': 'of1',
  13. 'price': 1},
  14. {'parent_id': 'c1', 'id': 'o11', 'type': 'offer', 'name': 'of11',
  15. 'price': 11},
  16. {'parent_id': 'c2', 'id': 'o2', 'type': 'offer', 'name': 'of2',
  17. 'price': 2},
  18. {'parent_id': 'c3', 'id': 'o3', 'type': 'offer', 'name': 'of3',
  19. 'price': 3},
  20. {'parent_id': 'c4', 'id': 'o4', 'type': 'offer', 'name': 'of4',
  21. 'price': 4},
  22. ]
  23.  
  24. result = {
  25. 'id': 'c1',
  26. 'name': 'cat1',
  27. 'parent_id': None,
  28. 'price': 0,
  29. 'children': []
  30. }
  31. # --- до сюда то что можем +- незапарно получить из базы ---
  32.  
  33.  
  34. def smart_map(iterator):
  35. """
  36. map, который возвращает цену товара и
  37. параллельно считает количество товаров
  38. :param iterator: offers
  39. :return:
  40. """
  41. global n
  42. for n, val in enumerate(iterator, start=1):
  43. yield val.get('price', 0)
  44.  
  45.  
  46. def config_category(category):
  47. cid = category['id']
  48. # Товаы, которые принадлежат нашей категории
  49. offers_parents = filter(lambda x: x['parent_id'] == cid,
  50. offers2categories)
  51. # Считаем сумму товаров и паралельно их количество
  52. s = sum(smart_map(offers_parents))
  53.  
  54. # Высчитываем среднюю цену товаров
  55. category['price'] = s // n
  56.  
  57. # Суммируем средние цены вложенных категорий и срденюю ценюу товаров
  58. if cid in children:
  59. old_n = n
  60. category['price'] += sum(smart_map(children.get(cid, [])))
  61. category['price'] //= n + old_n
  62.  
  63. # Добавляем товары категории
  64. category['children'].extend(filter(lambda x: x['parent_id'] == cid,
  65. offers2categories))
  66.  
  67. # Добавляем вложенные категории
  68. category['children'].extend(children.get(cid, []))
  69. return category
  70.  
  71.  
  72. children = {} # {parent_id: [child1, child2]}
  73. n = 0
  74. for i in range(len(categories) - 1, -1, -1):
  75. pre_res = {'children': [], 'price': 0}
  76. # Записываем саму категорию
  77. pre_res.update(categories[i])
  78. parent_id = pre_res['parent_id']
  79.  
  80. config_category(pre_res)
  81.  
  82. if parent_id not in children:
  83. children[parent_id] = [pre_res.copy()]
  84. else:
  85. children[parent_id].append(pre_res.copy())
  86.  
  87. config_category(result)
  88.  
  89. pprint.pprint(result)
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement