Calculating Series in Python

1

How to calculate series in Python? I've created an algorithm but I'm not making it to the end goal.

Ex:

S1 = x + (x-1) + (x – 2) + ... + (x – n) 
S2 = 1                     
asked by anonymous 01.12.2016 / 13:45

2 answers

1

The first series:

S1 = x + (x-1) + (x – 2) + ... + (x – n) 

It can be simplified so that the calculation is O (1) by grouping the terms in common:

S1 = x + (x-1) + (x – 2) + ... + (x – n) 
   = (x + x + x + ... + x) - (0 + 1 + 2 + ... + n)
   = (n+1)*x - n*(n+1)/2
   = (n+1)*(x - n/2)

That is, the result can be obtained only with some mathematical operations, 4, precisely, independent of the quantity of n , without having to implement some loop repetition that would leave the solution at least O (n).

In Python, this could be implemented even in a lambda expression:

S1 = lambda x, n: (n+1)*(x - n/2)

For example, S1(5, 3) will result in 14 because:

S1 = 5 + (5 - 1) + (5 - 2) + (5 - 3)
   = 5 + 4 + 3 + 2
   = 14

As a matter of curiosity, the loopback solution might be:

S1 = lambda x, n: sum(x-i for i in range(n+1))

As for series 2, I was unable to understand the notation used.

    
28.03.2018 / 04:09
0

According to your series example and using the same variables (x and n):

serie = 0
x = int(input("Digite o valor de x: "))
n = int(input("Digite o valor de n: "))

for i in range(1,n + 1):
    serie += x - i
    print("\nValor da serie +=", x, "-", i, "=", x - i)
    i += 1
print("\nValor da serie total =", serie)

See running on ideone

To make S2, simply reverse the subtractions for additions.

    
01.12.2016 / 14:24