Write this accumuator in a functional style

Ian Kelly ian.g.kelly at gmail.com
Tue Jul 11 13:18:45 EDT 2017


On Tue, Jul 11, 2017 at 12:47 AM, Wolfgang Maier
<wolfgang.maier at biologie.uni-freiburg.de> wrote:
> On 07/11/2017 08:11 AM, Steven D'Aprano wrote:
>>
>> I have a colleague who is allergic to mutating data structures. Yeah, I
>> know, he needs to just HTFU but I thought I'd humour him.
>>
>> Suppose I have an iterator that yields named tuples:
>>
>> Parrot(colour='blue', species='Norwegian', status='tired and shagged out')
>>
>> and I want to collect them by colour:
>>
>> accumulator = {'blue': [], 'green': [], 'red': []}
>> for parrot in parrots:
>>      accumulator[parrot.colour].append(parrot)
>>
>>
>> That's pretty compact and understandable, but it require mutating a bunch
>> of pre-allocated lists inside an accumulator. Can we re-write this in a
>> functional style?
>>
>> The obvious answer is "put it inside a function, then pretend it works by
>> magic" but my colleague's reply to that is "Yes, but I'll know that its
>> actually doing mutation inside the function".
>>
>>
>> Help me humour my colleague.
>>
>>
>>
>
> Hmm, isn't this just asking for itertools.groupby on the parrots sorted by
> colour?

That's one solution, but the sorting makes it O(n log n) for a task
that should really just be O(n).



More information about the Python-list mailing list