[Baypiggies] How to create a dict of counts using functional programming

Alex Martelli aleax at google.com
Mon Sep 28 16:01:07 CEST 2015


If for some weird reason in can't use collections.Counter, as David
sensibly suggests, the "FP way" (slow and cranky in Python, which doesn't
do tail-call optimization, NOT being a functional programming language) is
recursion:

_sentinel = object()

def _count_aux(it, adict):
    item = next(it, _sentinel)
    return adict if item is _sentinel else _count_aux(it, dict(adict,
*{item: adict.get(item, 0) + 1})
def count(iterable):
    return _count_aux(iter(iterable), {})

The assignment in _count_aux's first statement is needed because iterators
are not "peekable", and you need to refer to "the next item of the
iterator" three times in the return statement -- if the bet terms included
"totally avoid assignment" (I see no reason for the task except a weird
bet!-) you could add another aux function (using argument passing in lieu
of assignment, and making the recursion mutual).

Except for winning weird bets, there are no positive aspects in using such
a convoluted style in Python.


Alex


On Mon, Sep 28, 2015 at 4:01 AM, Braun Brelin <bbrelin at gmail.com> wrote:

> Hello all,
>
> I am trying to do the following:
> I have a list that looks like this:
> ['1','2','7','8','8']
>
> I want to create a dictionary that looks like this:
> {1:1, 2:1,7:1,8:2}
> i.e. the value is the count of the number of times the key appears in
> the list.  The catch is that I'm trying to do this in a functional
> programming way, rather than iteratively.
>
> I'm trying to use something like map, or reduce or even dict, but I can't
> figure out how to tell
> python to increment the value.  In other words how do I even specify what
> the value is, as it
> seems to be a bit of a chicken and egg scenario.
>
> I can, for example create a dictionary that sets the values to a constant,
> such as zero using FP,
> but how do I tell it to increment the value for a dictionary that doesn't
> yet exist as I'm in the process of
> building it?
>
> Thanks,
>
> Braun Brelin
>
>
>
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> https://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20150928/22706e15/attachment.html>


More information about the Baypiggies mailing list