Elliot Gorokhovsky
Elliot Gorokhovsky

Reputation: 3762

Avoid redundancy in this list comprehension

How can I avoid querying the set object sol unnecessarily in this list comprehension? Currently, I query it twice for each object, once in the ternary and once in the predicate. However, I cannot think of a more elegant solution. Is there one?

dnf = (
    (
        (
            d if p[i,d,True] in sol
            else
            -d if p[i,d,False] in sol
        )
        for d in range(N)
        if p[i,d,True] in sol or p[i,d,False] in sol
    )
    for i in range(M)
)

Upvotes: 2

Views: 94

Answers (1)

Ry-
Ry-

Reputation: 225263

You can identify that case with None and filter it out:

dnf = (
    (
        x for x in (
            d if p[i,d,True] in sol else
            -d if p[i,d,False] in sol else None
            for d in range(N)
        )
        if x is not None
    )
    for i in range(M)
)

Or chain iterables in one of various ways:

dnf = (
    (
        x
        for d in range(N)
        for x in (
            (d,) if p[i,d,True] in sol else
            (-d,) if p[i,d,False] in sol else ()
        )
    )
    for i in range(M)
)

But have you considered a function instead?

def get_dnf(N, p, sol, i):
    for d in range(N):
        if p[i,d,True] in sol:
            yield d
        elif p[i,d,False] in sol:
            yield -d


dnf = (get_dnf(N, p, sol, i) for i in range(M))

Upvotes: 7

Related Questions