Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>import string allowed = set(string.lowercase + ',') if set(text) - allowed: # you know it has forbidden characters else: # it doesn't have forbidden characters </code></pre> <p>Doing it with sets will be faster than doing it with for loops (especially if you want to check more than one text) and is all together cleaner than regexes for this situation.</p> <p>an alternative that might be faster than two sets, is </p> <pre><code>allowed = string.lowercase + ',' if not all(letter in allowed for letter in text): # you know it has forbidden characthers </code></pre> <p>here's some meaningless <code>mtimeit</code> results. <code>one</code> is the generator expression and <code>two</code> is the set based solution.</p> <pre><code>$ python -mtimeit -s'import scratch3' 'scratch3.one("asdfas2423452345sdfadf34")' 100000 loops, best of 3: 3.98 usec per loop $ python -mtimeit -s'import scratch3' 'scratch3.two("asdfas2423452345sdfadf34")' 100000 loops, best of 3: 4.39 usec per loop $ python -mtimeit -s'import scratch3' 'scratch3.two("asdfasasdfadsfasdfasdfdaf")' 100000 loops, best of 3: 3.51 usec per loop $ python -mtimeit -s'import scratch3' 'scratch3.one("asdfasasdfadsfasdfasdfdaf")' 100000 loops, best of 3: 7.7 usec per loop </code></pre> <p>You can see that the setbased one is significantly faster than the generator expression with a small expected alphabet and success conditions. the generator expression is faster with failures because it can bail. This is pretty much whats to be expected so it's interesting to see the numbers back it up.</p> <p>another possibility that I forgot about is the hybrid approach.</p> <pre><code>not all(letter in allowed for letter in set(text)) $ python -mtimeit -s'import scratch3' 'scratch3.three("asdfasasdfadsfasdfasdfdaf")' 100000 loops, best of 3: 5.06 usec per loop $ python -mtimeit -s'import scratch3' 'scratch3.three("asdfas2423452345sdfadf34")' 100000 loops, best of 3: 6.71 usec per loop </code></pre> <p>it slows down the best case-ish but speeds up the worst case-ish. All in all, you'd have to test the different possibilities over a sample of your expected input. the broader the sample, the better. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload