dict comprehension question.

Tim Chase python.list at tim.thechases.com
Sat Dec 29 19:26:37 EST 2012


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






More information about the Python-list mailing list