Skip to content

Instantly share code, notes, and snippets.

@zh4n7wm
Last active March 12, 2019 04:57
Show Gist options
  • Select an option

  • Save zh4n7wm/c2969486cd08efcaab3bf5d035bf3468 to your computer and use it in GitHub Desktop.

Select an option

Save zh4n7wm/c2969486cd08efcaab3bf5d035bf3468 to your computer and use it in GitHub Desktop.
The number of characters in string
import string
from collections import Counter, defaultdict
limited_chars = string.ascii_letters + string.digits
with open('test_1.txt') as fd:
content = fd.read()
def func_a(s):
ss = (x for x in s if x in limited_chars)
c = Counter(ss)
return c.most_common()
def func_b(s):
res = defaultdict(int)
for x in s:
if x not in limited_chars:
continue
res[x] += 1
return sorted(res.items(), key=lambda x: x[1], reverse=True)
def func_c(s):
res = {}
for x in s:
if x not in limited_chars:
continue
res[x] = res[x] + 1 if x in res else 1
return sorted(res.items(), key=lambda x: x[1], reverse=True)
@zh4n7wm

zh4n7wm commented Mar 12, 2019

Copy link
Copy Markdown
Author
[ins] In [6]: %timeit func_a(content)
1.29 ms ± 3.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

[nav] In [7]: %timeit func_b(content)
1.26 ms ± 28.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

[ins] In [8]: %timeit func_c(content)
1.39 ms ± 14.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@zh4n7wm

zh4n7wm commented Mar 12, 2019

Copy link
Copy Markdown
Author
import operator
sorted(res.items(), key=operator.itemgetter(1), reverse=True)
[(k, res[k]) for k in sorted(d, key=res.get, reverse=True)]  # just a way, slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment