list comprehention
Bryan Olson
fakeaddress at nowhere.org
Fri Jan 20 17:58:23 EST 2006
Duncan Booth wrote:
> Here's the way I would do it:
>
>>>>def occurrences(it):
>
> res = {}
> for item in it:
> if item in res:
> res[item] += 1
> else:
> res[item] = 1
> return res
I slightly prefer:
def occurrences(it):
res = {}
res[item] = res.get(item, 0) + 1
return res
[...]
> Or in other words, define a function to return a dictionary containing
> a count of the number of occurrences of each element in the list (this
> assumes that the list elements are hashable). Then you just add up the
> values in the test list making sure each count is limited to no higher than
> the reference count.
Resulting in a linear-time average case, where the posted
list-comprehension-based solutions are quadratic. The title
of the thread is unfortunate.
The generalized problem is multiset (AKA "bag") intersection:
http://en.wikipedia.org/wiki/Bag_(mathematics)
--
--Bryan
More information about the Python-list
mailing list