Advertisement
YaBoiSwayZ

RowLimitedAPIRequestGenerator v1

May 26th, 2024 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | Source Code | 0 0
  1. from itertools import combinations
  2.  
  3. def generate_combinations(variables, limit):
  4.     memo = {}
  5.  
  6.     def product_count(values):
  7.         count = 1
  8.         for value in values:
  9.             count *= len(value)
  10.         return count
  11.  
  12.     def combine_variables(vars_list):
  13.         if not vars_list:
  14.             return [{}]
  15.  
  16.         key = tuple((var, tuple(values)) for var, values in vars_list)
  17.         if key in memo:
  18.             return memo[key]
  19.  
  20.         results = []
  21.         current_var, options = vars_list[0]
  22.         for subset in (combinations(options, i) for i in range(1, len(options) + 1)):
  23.             for option in subset:
  24.                 if product_count([option]) > limit:
  25.                     break
  26.                 for result in combine_variables(vars_list[1:]):
  27.                     new_combination = {current_var: option, **result}
  28.                     if product_count(new_combination.values()) <= limit:
  29.                         results.append(new_combination)
  30.         memo[key] = results
  31.         return results
  32.  
  33.     all_combinations = combine_variables(list(variables.items()))
  34.  
  35.     def merge_combinations(combinations):
  36.         merged = []
  37.         for combo in combinations:
  38.             if not any(all(set(combo[var]).issubset(m[var]) for var in combo) for m in merged):
  39.                 merged.append(combo)
  40.         return merged
  41.  
  42.     return merge_combinations(all_combinations)
  43.  
  44. variables = {
  45.     "gender": ["total", "women", "men"],
  46.     "country of birth": ["Norway", "Finland", "Sweden", "Denmark"],
  47.     "year": ["2019", "2020", "2021", "2022", "2023"]
  48. }
  49.  
  50. row_limit = 13
  51.  
  52. optimal_configs = generate_combinations(variables, row_limit)
  53. print(f"Optimal Request Configurations (Total: {len(optimal_configs)}):")
  54. for config in optimal_configs:
  55.     print(config)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement