5

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?

0

1 Answer 1

13
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).
Sign up to request clarification or add additional context in comments.

2 Comments

I just happen to figure it out that sum((m - r + 1) * (n - r + 1) for r in range(1,n+1)) too works.
The difference between the two is that in Python 2.x, range returns an actual list, which may be quite wasteful of memory if the list is large. xrange is an iterable which generates the numbers in order rather than actually returning a real list. (In Python 3, xrange goes away and range becomes a memory efficient iterable)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.