Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let me start off by saying that I suspect that you are optimizing when you don't need to. Python is a high-level language that supports thinking about computation in a high-level manner. A solution that is readable, elegant, and reusable is often going to be better than one that is blazingly fast, but hard to understand.</p> <p>When, and <strong>only</strong> when, you determine that speed is an issue, then you should proceed with the optimizations. Perhaps even write a C extension for the computationally intense parts.</p> <p>That being said, here's a comparison of a few techniques:</p> <pre><code>def unique_chars_set(s): return len(s) == len(set(s)) def unique_chars_frozenset(s): return len(s) == len(frozenset(s)) def unique_chars_counter(s): return Counter(s).most_common(1)[0][1] &gt; 1 def unique_chars_sort(s): ss = ''.join(sorted(s)) prev = '' for c in ss: if c == prev: return False prev = c return True def unique_chars_bucket(s): buckets = 255 * [False] for c in s: o = ord(c) if buckets[o]: return False buckets[o] = True return True </code></pre> <p>And here is the performance comparisons (in IPython):</p> <pre><code>In [0]: %timeit -r10 [unique_chars_set(s) for s in candidate_strings] 100000 loops, best of 10: 6.63 us per loop In [1]: %timeit -r10 [unique_chars_frozenset(s) for s in candidate_strings] 100000 loops, best of 10: 6.81 us per loop In [2]: %timeit -r10 [unique_chars_counter(s) for s in candidate_strings] 10000 loops, best of 10: 83.1 us per loop In [3]: %timeit -r10 [unique_chars_sort(s) for s in candidate_strings] 100000 loops, best of 10: 13.1 us per loop In [4]: %timeit -r10 [unique_chars_bucket(s) for s in candidate_strings] 100000 loops, best of 10: 15 us per loop </code></pre> <p>Conclusion: <code>set</code> is elegant and faster than many other obvious methods. But the differences are so small, it doesn't matter anyway.</p> <p>For more benchmarks, see <a href="https://stackoverflow.com/a/15751669/716118">@FrancisAvila</a>'s answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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