Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Counting frequency in a list

   1  
   2  >>> alist = [ '1', '1', '2', '1', '3', '4', '1', '3']
   3  >>> [(a, alist.count(a)) for a in set(alist)]
   4  [('1', 4), ('3', 2), ('2', 1), ('4', 1)]
   5  >>> sorted(_, key=lambda x: -x[1])  # rank them
   6  [('1', 4), ('3', 2), ('2', 1), ('4', 1)]

Counting number of bitmaps in an mbm file

I continue my hacking on symbian mbm(multi-bitmap) format.
   1  
   2  # a helping function
   3  from struct import unpack
   4  def readL(f, pos=None):
   5      if pos is not None:
   6          f.seek(pos)
   7      return unpack('L', f.read(4))[0]
   8  
   9  # the real counting function
  10  def mbm_count(mbm_file):
  11      f = open(mbm_file, 'rb')
  12      mbm_type = readL(f)
  13      if mbm_type == 0x10000041:  # mbm on ROM (Z:)
  14          return readL(f) 
  15      elif mbm_type == 0x10000037L:  # mbm on file (normal)
  16          return readL(f, readL(f, 16)) # read at trailer
  17      else:       # what type is it?
  18          return None

For example (you may try this on your phone)
   1  
   2  >>> mbm_count('z:\\system\\data\\avkon.mbm')
   3  503L
   4  >>> mbm_count('E:\\system\\apps\\FExplorer\\FExplorer.mbm')
   5  19L
   6  >>>

Counting characters in string

   1  
   2  >>> s = 'a;jfkd;aflhakfhaskfjalghlakfhfnkjafyksd'
   3  >>> cnt = {}
   4  >>> for c in s:
   5  	cnt[c] = cnt.get(c,0) + 1
   6  
   7  >>> print cnt
   8  {'a': 7, 'd': 2, 'g': 1, 'f': 7, 'h': 4, 'k': 6, 'j': 3, 'l': 3, 'n': 1, 's': 2, 'y': 1, ';': 2}

This can be used to count any distribution.
Note the use of dict.get(key,default) to set to 0
if the key is not avaiable.
If this were perl, I would just do a
   1  cnt[c] += 1

But python will give an error instead of returning 0.
It's not too bad, though.
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS