Python 中 __add__ 的三元(以及更多!)重载
背景:
作为一个个人学习项目,我一直在研究一个简单的计算机代数系统。我有一个单变量多项式类,其中项的系数存储为字典。重载两个多项式 A 和 B 之和的运算符涉及查找相似项,将它们相加,并为 A 或 B 中的项创建一个新项,但不能同时为两者 (XOR)。这按预期工作,但是...
问题:
我注意到当我想添加两个以上多项式时,过程很慢,因为有一个可以同时完成的通用计算。例如,给定四个多项式 (A、B、C、D),sum: 的
A + B + C + D
计算结果为:
((A+B) + C) + D
换句话说:
add(add(add(A,B),C),D)
我可以编写一个在存在多个求和时调用的 add 函数的特殊重载吗?
add(A,B,C,D)
Context:
As a personal learning project I've been working on a simple computer algebra system. I have a univariate polynomial class where the coefficents to the terms are stored as a dictionary. Operator overloading the sum of two polynomials A and B involves finding the like terms, adding them and making a new term for the terms in A or B but not both (XOR). This works as expected but...
Question:
I noticed when I wanted to add more then two polynomials the process is slow as there is a common computation that could be done simultaneously. For example, given four polynomials (A,B,C,D) the sum:
A + B + C + D
is evaluated as:
((A+B) + C) + D
in other words:
add(add(add(A,B),C),D)
Could I write a special overload of the add function that would be called when there are multiple summations?
add(A,B,C,D)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之:否
这是所有运算符和参数的列表: http: //docs.python.org/reference/datamodel.html#emulated-numeric-types
使用自定义函数是您唯一的选择
In short: No
Here's the list of all the operators and the parameters: http://docs.python.org/reference/datamodel.html#emulating-numeric-types
Using a custom function is your only option
它(在某种程度上)可以通过一些黑客攻击......
基本上,该过程是在初始计算后不返回值 - 而是返回一个承诺,即您将在某个时刻计算该值。
因此,
a + b
将返回一个表示要完成的计算的对象(但实际上并不执行计算),我将其称为(+ ab)
。然后,当计算下一个加法时,我们最终得到
(+ ab) + c
,其计算结果为(+ abc)
,依此类推。仅当访问结果的属性时,您才真正执行计算。
It's (sort of) doable with some hacking...
Basically the process is to not return a value after the initial computation - but rather, to return a promise that you'll compute the value at some point.
So
a + b
will return an object representing the calculation to be done (but not actually performing the calculation), which I'll call(+ a b)
.Then when it comes to evaluate the next addition, we end up with
(+ a b) + c
which evaluates to(+ a b c)
, and so on.Only when a property of the result is accessed do you actually carry out the computation.
您是否真正分析过代码以找出瓶颈所在? python 中的函数调用相当快。
Have you actually profiled the code to figure out where your bottleneck is? Function calls in python are fairly fast.
您可以使用reduce内置函数,
例如reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
它将计算 ((((1+2)+3)+4)+5)。
有关它的更多信息,您可以从这里获取: http://docs.python.org/library /functions.html#reduce
You can use reduce built-in function
like this reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
and it will calculates ((((1+2)+3)+4)+5).
more information about it you can get from here : http://docs.python.org/library/functions.html#reduce