Remove all collection elements that contain a specific char

I have a set of several thousand primes generated by a generator:

primes = set(primegen()) = set([..., 89, 97, 101, 103, ...])

Some of these primes have zero in them. I would like to get rid of them. Is there any way to do this all at once?

I am currently deleting elements when I loop through primes, with a regex:

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 I am curious if I am wrong.

+4
source share
5 answers

Summarizing and timing of responses:

With the first 100,000 primes. (Using timeit and copying prime numbers every time)

root

primes = {p for p in primes if '0' not in str(p)}

10 loops, best 3: 29.6 ms per cycle

Mike

while primes:
    p = str(primes.pop())
    if '0' in p:
        continue
    # do other stuff

10 , 3: 38,9

R

filter(lambda x: '0' not in str(x), primes)

1000 , 3: 963

Kasramvd

def zero_membership_checker(num):
    while num:
        if num%10 == 0:
            return True
        num = num / 10
    return False

1 , 3: 6.65

hiyume

import re
zero = re.compile('.+0.+') 

while primes:
    p = str(primes.pop())
    if zero.match(p):
        continue
    # do other stuff

10 , 3: 69,4

+1

.

primes = {p for p in primes if '0' not in str(p)}
+8

: , . , , 101 103 primes, .

. :

# 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 , .

, , , . itertools (.. , , ):

from itertools import imap, ifilter
filtered_primes = imap(int,
                       ifilter(lambda p: "0" not in p,
                               imap(str, primes)))

, , , ( ):

filteres_primes = (p for p in primes if "0" not in str(p))
+3

(, , in ), , . , , , :

>>> def zero_membership_checker(num):
...     while num:
...         if num%10 == 0:
...             return True
...         num = num / 10
...     return False
... 
>>> s = set([89, 97, 101, 103])
>>> 
>>> {i for i in s if not zero_membership_checker(i)}
set([89, 97])
+1

filter :

In [25]: primes = set([83, 89, 97, 101, 103])

In [26]: filter(lambda x: '0' not in str(x), primes)
Out[26]: [89, 83, 97]

, ,

In [37]: %timeit filter(lambda x: '0' not in str(x), myList)
10 loops, best of 3: 23.7 ms per loop

In [38]: %timeit {p for p in myList if '0' not in str(p)}
10 loops, best of 3: 22 ms per loop
+1

All Articles