from typing import Any, Collection, Iterator, List, TypeVar, cast import act4e_interfaces as I from .sets_product import MyFiniteSetProduct E = TypeVar("E") class MyFiniteSet(I.FiniteSet[E]): _elements: List[E] def __init__(self, elements: Collection[E]): self._elements = elements def size(self) -> int: return len(self._elements) def contains(self, x: E) -> bool: return any(map(lambda y: y == x, self._elements)) def elements(self) -> Iterator[E]: return self._elements def save(self, h: I.IOHelper, x: E) -> List[E]: return cast(I.ConcreteRepr, x) def load(self, h: I.IOHelper, o: I.ConcreteRepr): return cast(E, o) class SolFiniteSetRepresentation(I.FiniteSetRepresentation): def load(self, h: I.IOHelper, data: I.FiniteSet_desc) -> I.FiniteSet[Any]: if not isinstance(data, dict): raise I.InvalidFormat() if "elements" in data: if not isinstance(data["elements"], list): raise I.InvalidFormat() elements = data["elements"] return MyFiniteSet(elements) elif "product" in data: if not isinstance(data["product"], list): raise I.InvalidFormat() components = [] for comp in data["product"]: if not isinstance(comp, dict): raise I.InvalidFormat() if not "elements" in comp: raise I.InvalidFormat() if not isinstance(comp["elements"], list): raise I.InvalidFormat() components.append(MyFiniteSet(comp["elements"])) return MyFiniteSetProduct(components) else: raise I.InvalidFormat() def save(self, h: I.IOHelper, f: I.FiniteSet[Any]) -> I.FiniteSet_desc: if isinstance(f, MyFiniteSetProduct): return {"product": [{"elements": c.elements()} for c in f.components()]} elif isinstance(f, MyFiniteSet): all_elements = [f.save(h, e) for e in f.elements()] return {"elements": all_elements} else: raise I.InvalidFormat()