Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements of a set that contain a specific char

Tags:

python

set

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.

like image 703
ehacinom Avatar asked Dec 05 '22 01:12

ehacinom


2 Answers

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)}
like image 180
root Avatar answered May 13 '23 21:05

root


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))
like image 20
Carsten Avatar answered May 13 '23 21:05

Carsten