开发者

Sum() in python

I have been trying to be comfortable with the sum() in python, I did understand the basic function of sum but as a mathematica backgroud,I was just inquistive to know can we use sum in python in the same way like we do in mathematica for example consider this mathematica module:

Sq[a_, b_] := Module[{m, n}, m = Max[a, b]; n = Min[a, b];Sum[(m - r + 1) (n - r + 1), {r, 1, n}]]

Now,could it be possible to write the sum part like that? I mean:

Sum[(m - r + 1) (n - r + 1), {r, 1, n}]

Trying to covert this in python,I think of something like this:

开发者_Python百科sum((m - r + 1) (n - r + 1) in xrange(1,n+1)) 

but doesn't seems to be working! so my question how to get it work?


sum((m - r + 1) * (n - r + 1) for r in xrange(1,n+1))
  1. There's no implicit multiplication between integers, so you need the *.
  2. f(x) for x in xes is the general format of a list comprehension, where you want x to iterate through every element of xes, and give back the value f(x).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜