Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

finding most common elements between thousands of multiple arrays.

 

 

First page Previous page 1 2 Next page Last page  View All Python python RSS feed   Index | Next | Previous | View Threaded


python at rcn

Jul 8, 2009, 12:11 AM

Post #26 of 27 (264 views)
Permalink
Re: finding most common elements between thousands of multiple arrays. [In reply to]

[Scott David Daniels]
> def most_frequent(arr, N):
>      '''Return the top N (freq, val) elements in arr'''
>      counted = frequency(arr) # get an iterator for freq-val pairs
>      heap = []
>      # First, just fill up the array with the first N distinct
>      for i in range(N):
>          try:
>              heap.append(counted.next())
>          except StopIteration:
>              break # If we run out here, no need for a heap
>      else:
>          # more to go, switch to a min-heap, and replace the least
>          # element every time we find something better
>          heapq.heapify(heap)
>          for pair in counted:
>              if pair > heap[0]:
>                  heapq.heapreplace(heap, pair)
>      return sorted(heap, reverse=True) # put most frequent first.

In Py2.4 and later, see heapq.nlargest().
In Py3.1, see collections.Counter(data).most_common(n)


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


Scott.Daniels at Acm

Jul 10, 2009, 1:38 PM

Post #27 of 27 (259 views)
Permalink
Re: finding most common elements between thousands of multiple arrays. [In reply to]

Raymond Hettinger wrote:
> [Scott David Daniels]
>> def most_frequent(arr, N): ...
> In Py2.4 and later, see heapq.nlargest().
I should have remembered this one

> In Py3.1, see collections.Counter(data).most_common(n)
This one is from Py3.2, I think.


--Scott David Daniels
Scott.Daniels [at] Acm
--
http://mail.python.org/mailman/listinfo/python-list

First page Previous page 1 2 Next page Last page  View All Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.