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
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