2

My code is as follows. It loops through blobs which is set of frozenset and check if each blob intersects with mapped which is a set. If a blob does intersects with mapped and also satisfies the condition of being terminal, then add the intersection set to the result.

result = set()
for b in blobs:                                                   
    mapped_b = b & mapped                                                 
    if mapped_b and _is_terminal(mapped_b):                          
        result.add(mapped_b)

Can this logic be written in a better way? I was thinking of list comprehension, but since mapped_b is formed on the go, it seems I have to make it multiple times which is wasteful.

[result.add(b&mapped) for b in blobs if b&mapped and _is_terminal(b&mapped)]

Also is it worth the trouble to use filter for the if statement?

1 Answer 1

3

As far as I know, there is no such thing as a let statement (like for instance in Haskell) that would allow to temporary store the mapped_b result.

You can however use map or a generator to store the intermediate result. Like:

result = {mapped_b for mapped_b in map(lambda b:b&mapped,blobs) if mapped_b and _is_terminal(mapped_b)}

So map(lambda b:b&mapped,blobs) will generate the mapped_b items (in one at a time, in with a temprorary list).

Or you can use a generator yourself:

result = {mapped_b for mapped_b in (b&mapped for b in blobs) if mapped_b and _is_terminal(mapped_b)}

Note that we here use set comprehension, not list comprehension. In the original code fragment, you also construct a set.

EDIT:

based on your comment, you can indeed omit the if part by using a filter like:

result = set(filter(lambda b: b and _is_terminal(b),(b&mapped for b in blobs)))

This is semantically equivalent. Whether one is preferred over the other is usually an aspect of taste. Here the two are easily interchangeable.

Sign up to request clarification or add additional context in comments.

4 Comments

What do you think about result=set(filter(lambda b: if b and _is_terminal(b), (b&mapped for b in blobs)))? Is it bad code?
not per se, but my experience is that set comprehension is usually more efficient (and more elegant as well). Afaik filter will not boost the process (much). But it will have semantically the same result.
@nos: note that you should drop the if in the lambda of the filter.
Yes, that's a typo. Thank you very much for all the information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.