Question

I am trying to queue some mathematical expressions somewhere into python and then in the end I would like to show their summation.

I am trying to do something like this:

for i in range(0, n-1): sum_queue(pow(-1,i)/((2*i)+1))
print(sum(0)) #or sum("latest")

Is it possible?

No correct solution

OTHER TIPS

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
>>> queue = []
>>> n = 10
>>> for i in range(0, n-1):
...     queue.append(pow(-1,i)/((2*i)+1))
... 
>>> queue
[1, -1, 0, -1, 0, -1, 0, -1, 0]
>>> sum(queue)
-3
>>> queue = [pow(-1,i)/((2*i)+1) for i in range(0, n-1)]
>>> sum(queue)
-3
>>> 

If you don't need the temporary list, you can use a generator:

>>> sum(pow(-1,i)/((2*i)+1) for i in range(0, n-1))
-3

Following my comment to @warwaruk's answer, this can be shortened to use a counter. Although it defeats the purpose of using a queue, since the only operation here is going to be summing the values, the queue is not necessarily needed.

Technically, the queue wouldn't be needed if you're going to perform any type of arithmetic operation on all the values following the append()

n = 10;
total = 0;
for i in range(0,n-1): 
  total += (pow(-1,i)/((2*i)+1));
print(total);

Instead of appending the values to the queue and then sum()ing it, this does it all together within the same for loop.

If you want to take a look at asymptotic analysis, they are both O(n), but this code is shorter and will save you a function call plus another O(n) operation.

Hopefully this answers your question :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top