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))
- There's no implicit multiplication between integers, so you need the
*
. f(x) for x in xes
is the general format of a list comprehension, where you wantx
to iterate through every element ofxes
, and give back the valuef(x)
.
精彩评论