Advertisement
gg-master

Untitled

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