I have a set of a few thousand primes generated from a generator:
primes = set(primegen()) = set([..., 89, 97, 101, 103, ...])
Some of those primes have a zero in them. I would like to get rid of them. Is there a way to do this all at once?
Currently I am removing elements as I loop through primes, with a regex match:
import re
zero = re.compile('.+0.+')
while primes:
p = str(primes.pop())
if zero.match(p):
continue
# do other stuff
I think this is the best way, but am curious if I'm wrong.
You could use a set comprehension to filter your existing set of primes.
primes = {p for p in primes if '0' not in str(p)}
Disclaimer: I have absolutely no idea what you want to do with this or why this would be useful. I just assume that you want to remove numbers like 101
and 103
from your primes
set because they contain a zero digit.
You don't even need regexes for that. It can be done with a simple list comprehension:
# assume that primes is defined
str_primes = map(str, primes)
filtered_str_primes = [p for p in primes if "0" not in p]
filtered_primes = map(int, primes)
Kasramvd's answer might be faster, you shoud test both out.
I'm not sure if your set is just an example or if you plan to use a generator to produce a possibly infinite list of primes. In the latter case, you can use itertools
to define the filtered sequence lazily (that is, in will only generate the next element when you ask for it instead of consuming the whole list):
from itertools import imap, ifilter
filtered_primes = imap(int,
ifilter(lambda p: "0" not in p,
imap(str, primes)))
Wait, I forgot, this should yield the same outcome, but with less code (I'll leave the older solution for completeness):
filteres_primes = (p for p in primes if "0" not in str(p))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With