On 12/29/12 15:40, Mitya Sirenef wrote:
      >>> w = [1,2,3,1,2,4,4,5,6,1]
      >>> s = set(w)
      >>> s
      set([1, 2, 3, 4, 5, 6])
      >>> {x:w.count(x) for x in s}
      {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

Indeed, this is much better -- I didn't think of it..

Except that you're still overwhelmed by iterating over every element in "w" for every distinct element. So you've gone from O(N**2) to O(k*N).

The cleanest way to write it (IMHO) is MRAB's

 >>> w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
 >>> from collections import Counter
 >>> results = dict(Counter(w))

which should gather all the statistics in one single pass across "w" making it O(N), and it's Pythonically readable.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to