Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum() in python

Tags:

python

sum

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:

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?

like image 351
Quixotic Avatar asked Dec 12 '22 13:12

Quixotic


1 Answers

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).
like image 169
Sebastian Paaske Tørholm Avatar answered Jan 08 '23 08:01

Sebastian Paaske Tørholm