Advertisement
gg-master

Untitled

Jun 17th, 2022
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.71 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. children = {} # {parent_id: [child1, child2]}
  47. n = 0
  48. for i in range(len(categories) - 1, -1, -1):
  49. pre_res = {'children': [], 'price': 0}
  50. # Записываем саму категорию
  51. pre_res.update(categories[i])
  52.  
  53. curr_id = pre_res['id']
  54. parent_id = pre_res['parent_id']
  55.  
  56. # Товаы, которые принадлежат нашей категории
  57. offers_parents = filter(lambda x: x['parent_id'] == curr_id,
  58. offers2categories)
  59. # Считаем сумму товаров и паралельно их количество
  60. s = sum(smart_map(offers_parents))
  61. # Высчитываем среднюю цену товаров
  62. pre_res['price'] = s // n
  63.  
  64. # Суммируем средние цены вложенных категорий и срденюю ценюу товаров
  65. if curr_id in children:
  66. old_n = n
  67. pre_res['price'] += sum(smart_map(children.get(curr_id, [])))
  68. pre_res['price'] //= n + old_n
  69.  
  70. # Добавляем товары категории
  71. pre_res['children'].extend(filter(lambda x: x['parent_id'] == curr_id,
  72. offers2categories))
  73.  
  74. # Добавляем вложенные категории
  75. pre_res['children'].extend(children.get(curr_id, []))
  76.  
  77. if parent_id not in children:
  78. children[parent_id] = [pre_res.copy()]
  79. else:
  80. children[parent_id].append(pre_res.copy())
  81.  
  82.  
  83. # Товаы, которые принадлежат нашей категории
  84. offers_parents = filter(lambda x: x['parent_id'] == result['id'],
  85. offers2categories)
  86. # Считаем сумму товаров и паралельно их количество
  87. s = sum(smart_map(offers_parents))
  88. # Высчитываем среднюю цену товаров
  89. result['price'] = s // n
  90. old_n = n
  91. result['price'] += sum(smart_map(children.get(result['id'], [])))
  92. result['price'] //= n + old_n
  93.  
  94. # Добавляем товары категории
  95. result['children'].extend(filter(lambda x: x['parent_id'] == result['id'],
  96. offers2categories))
  97.  
  98. # Добавляем вложенные категории
  99. result['children'].extend(children[result['id']])
  100.  
  101. pprint.pprint(result)
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement