Advertisement
xathrya

Character occurrence count

Oct 22nd, 2016
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.35 KB | None | 0 0
  1. # Count occurrence of character in a string.
  2. # Ex: 'Hello World!' would have 2 'o'
  3.  
  4. import itertools
  5. S = 'Hello World!'
  6.  
  7. # Sort the string so each character comes consecutively
  8. srt = ''.join(sorted(S))
  9.  
  10. # Group each characters
  11. grp = [ ''.join(grp) for num, grp in itertools.groupby(srt)]
  12.  
  13. # Count each group
  14. hasil = map(lambda x: (x[0], len(x)), grp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement