from itertools import combinations, repeat import random from typing import Any, Final, Iterable from collections import Counter from icecream import ic sets_count: Final[int] = random.randint(2, 1000) elements_count: Final[Iterable[int]] = (random.randint(3, 10000) for _ in repeat(None, sets_count)) ic(sets_count) sets: list[set[int]] = [ set( random.sample(range(-2_000_000_000, 2_000_000_000 + 1), count) ) for count in elements_count ] elements_to_sets: dict[int, list[int]] = {} pair_counts: Counter[tuple[int, int]] = Counter() for i, set_ in enumerate(sets): for element in set_: elements_to_sets.setdefault(element, list()).append(i) ic(len(elements_to_sets)) for sets_ in filter(lambda x: len(x) > 1, elements_to_sets.values()): pair_counts.update(combinations(sets_, 2)) sets_with_most_intersections: list[tuple[Any, int]] = pair_counts.most_common(1) if sets_with_most_intersections: max_intersection: int = sets_with_most_intersections[0][1] else: max_intersection = 0 print(max_intersection)