[Python-ideas] Implementing a set of operation (+, /, - *) on dict consistent with linearAlgebrae

julien tayon julien at tayon.net
Tue Oct 30 20:22:28 EDT 2018


On Wed, 31 Oct 2018 at 00:20, David Mertz <mertz at gnosis.cx> wrote:

> Counter doesn't QUITE do the same thing as this `mdict`.  But it's pretty
> close.
>
> I think if .__add__() became a synonym for .update() that wouldn't break
> anything that currently works.  But I'm probably wrong, and missing a case
> in my quick thought:
>
> My quick thoughts too is that it achieve coincidently Counter features as
a subset of its features. I never noticed it, and both approaches seem
consistent in their results (pfiou, close one since I did not thought of
checking it)

And .... if you add the trait to Counter .... you have the following
results :
>>> from collections import Counter
>
> >>> from archery.quiver import LinearAlgebrae
>>> class ACounter(LinearAlgebrae, Counter): pass

> >>> c = ACounter(a=[2], b='a')
> >>> c.update(c)
> >>> c
>

 ACounter({'a': [2, 2], 'b': 'aa'})
 (same)

>>> c2 = ACounter(a=1, b=2)
> >>> c2 + c2
>
ACounter({'b': 4, 'a': 2})

> >>> c2.update(c2)
> >>> c2
>
 ACounter({'b': 4, 'a': 2})

> >>> c2 + c2
>
ACounter({'a': 4, 'b': 8})
>>> c2 + .5 * c2
 ACounter({'a': 1.5, 'b': 3.0})


On Tue, Oct 30, 2018 at 6:54 PM Alexander Belopolsky <
> alexander.belopolsky at gmail.com> wrote:
>
>> > In [12]: a= mdict(a=[2], b='a')
>> > In [13]: a+a
>>
>> Aren't you reinventing the Counter type?
>>
>> nop. It is an unintended subset of the possibilities.
I do have though
>>> c2 / 2
Out[17]: ACounter({'a': 0.5, 'b': 1.0})
>>> c / 2
TypeError: can't multiply sequence by non-int of type 'float'

And talking about Counter, by inheriting from the mixins of Vector (dot,
abs, cos) we give it out of the box the cosine simlarities.

Which given its wide use in textual indexation is pretty reassuring. It
would also enable to normalize Counter (with value that supports truediv)
easily by writing

>>> class VCounter(LinearAlgebrae,Vector, Counter): pass
>>> c2 = VCounter(a=1, b=2)
>>> c2/abs(c2)
Out[20]: VCounter({'a': 0.4472135954999579, 'b': 0.8944271909999159})
And since it is mixins it touches nothing of the MutableMapping class it
relies on. It just gives behaviours associated with operators.
(ofc c2.cos(c) willl normally raise a TypeError since it would have no
sense)

It really is a proof of concept of adding linear/vectorial algebrae to ANY
kind of mutable mapping be it : dict, Counter, OrderedDict, defaultDict ...
It only relies on what mutableMapping (from abc) offers and does its life
with it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181031/35af200b/attachment-0001.html>


More information about the Python-ideas mailing list