Python: partition an iterable

Sep 28, 2015 20:43

"Partition" an iterable into two sets according to some predicate. (Ab)using the fact that set.add returns None.

bad = set()
good = {x for x in it if is_good(x) or bad.add(x)}

python

Leave a comment

Comments 2

or else... ext_3369314 November 3 2015, 21:21:34 UTC
source=[1,2,6,9,12,47]

good = set()
bad=set()

def is_good(n): return (n % 3) == 0

for s in source:
(good if is_good(s) else bad).add(s)

print "good = " + str(good)
print "bad = " + str(bad)

Reply

Re: or else... aklepatc November 4 2015, 01:11:23 UTC
It is_good: )
I am in love with list/set/dict comprehensions. So everything looks like a nail ;)
For a more technical point compare dis results for this:

def foo(it, bad):
return {x for x in it if is_good(x) or bad.add(x)}
and that:

def bar(it, bad):
good = set()
for x in it:
(good if is_good(x) else bad).add(x)
return good
You will be impressed by the difference.

Reply


Leave a comment

Up