mwchase icon

Too much itertools

mwchase | PRO | 10/02/16 02:34:16 AM UTC | 0 ⭐ | 827 👁️ | Never ⏰ | []
Python |

1.36 KB

|

None

|

0 👍

/

0 👎

    def __new__(cls, iterable=()): 
        if isinstance(iterable, cls): 
            return iterable 
        iterable = frozenset( 
            item for item in iterable if Conjunction() != item) 
        for clause in iterable: 
            assert isinstance(clause, Disjunction) 
        bins = sorted((i, tuple(g)) for (i, g) in itertools.groupby( 
            iterable, lambda clause: len(clause.terms))) 
        output = frozenset() 
        while bins: 
            bin = bins.pop() 
            intersections = () 
            non_compressed = set(bin[1]) 
            for fst, snd in itertools.combinations(bin[1], 2): 
                diff = list(fst.terms.symmetric_difference(snd.terms)) 
                if (len(diff) == 2 and 
                        Conjunction.cast(diff[0]) == not_(diff[1])): 
                    intersections += Disjunction( 
                        fst.terms.intersection(snd.terms)), 
                    non_compressed.discard(fst) 
                    non_compressed.discard(snd) 
            output = output.union(non_compressed) 
            if intersections: 
                if bins and bins[-1][0] == bin[0] - 1: 
                    bins[-1] = bins[-1][0], bins[-1][1] + intersections 
                else: 
                    bins.append((bin[0] - 1, intersections)) 
        return super().__new__(cls, output)

Comments