summaryrefslogtreecommitdiffstats
path: root/src/act4e_solutions/sets_representation.py
blob: 9e231c1efabd534c64d91fffbd671563ffd3b0cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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:
        all_elements = [f.save(h, e) for e in f.elements()]
        return {"elements": all_elements}