Advertisement
niedzwiedzw

Untitled

Jul 27th, 2022
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from random import choice
  3. from collections import defaultdict
  4. from datetime import datetime
  5. from dataclasses import dataclass
  6. ALL_CATEGORIES = [f'category-{i}' for i in range(5000)]
  7. # z requesta
  8. REQUIRED = [f'category-{i}' for i in range(500)]
  9.  
  10.  
  11. @dataclass(frozen = True)
  12. class Product:
  13.     name: str
  14.     id: int
  15.     category: str
  16.  
  17. def generate_product(idx: int) -> Product:
  18.     return Product(f'product-{idx}', idx, choice(ALL_CATEGORIES))
  19.  
  20. DATABASE_ITEMS_COUNT = 5000000
  21.  
  22.  
  23. def rozwiazanie_pieprzyk():
  24.     print('rozwiazanie pieprzyk')
  25.     required_categories = set(REQUIRED)
  26.     products_by_category = {}
  27.     for product in [generate_product(i) for i in range(DATABASE_ITEMS_COUNT)]:
  28.         if product.category not in required_categories:
  29.             continue
  30.         products_by_category.setdefault(product.category, [])
  31.         products_by_category[product.category].append(product)
  32.     len_all = DATABASE_ITEMS_COUNT
  33.     len_found = 0
  34.     for required_category in required_categories:
  35.         len_found += len(products_by_category[required_category])
  36.     print(f'znaleziono {len_found}/{len_all} produktów ({(len_found / len_all) * 100}%)')
  37.  
  38.  
  39. def rozwiazanie_niedzwiedz():
  40.     print('rozwiazanie niedzwiedz')
  41.     required_categories = set(REQUIRED)
  42.     database_products = (generate_product(i) for i in range(DATABASE_ITEMS_COUNT))
  43.     len_found = sum((
  44.         1 for product in database_products if product.category in required_categories
  45.     ))
  46.     len_all = DATABASE_ITEMS_COUNT
  47.     print(
  48.         f'znaleziono {len_found}/{len_all} produktów ({(len_found / len_all) * 100}%)'
  49.     )
  50.  
  51.  
  52. start = datetime.now()
  53. rozwiazanie_pieprzyk()
  54. print('koniec:', datetime.now() - start)
  55.  
  56.  
  57. start = datetime.now()
  58. rozwiazanie_niedzwiedz()
  59. print('koniec:', datetime.now() - start)
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement