Loop of sums - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Loop of sums (/thread-16936.html) |
Loop of sums - MathFreak - Mar-20-2019 Hello, I have a formula I would like to code in in Python. It is in the image in the link below, I couldn't type it because it uses math symbols: https://drive.google.com/file/d/1Y8ell0bII6zAZDZypcbH9iExuBVeRSGI/view?usp=sharing I am looking for a[m], which is the number of the array "a" at the index m. N is the maximal index of the array, it starts at 0. We have N>0 and m>=1. If N =1, then the values are: a[0]=1 a[1]=1 and we don't need the formula. If N>1 and m>=1 then we use the formula. Here is my code, but it doesn't work. I'm not sure if I'm going in the right direction. Thank you :) def polynomial_with_roots(N, m): a = [0 for x in range (N+1)] mySum = [0 for y in range (N+1)] mySecondSum = [0 for z in range (N+1)] a[0]=1 if m==0: a[0]=1 elif N==1: a=[1,1] elif m>=2: for i in range (1,m+1): print("i=",i) for kprevious in range (i,N+1): print("kprevious=",kprevious) for k in range (kprevious,N+1): print("k=",k) mySum[i]=mySum[i]+k print("mySum[i]",mySum[i]) mySecondSum[kprevious]=(kprevious-i+1)*mySum[i] a[i]=mySecondSum[kprevious] a[m]=a[i] print("a =",a) return a[m] polynomial_with_roots(2, 1) RE: Loop of sums - Yoriz - Mar-20-2019 Could you emphasise on "it doesn't work", what is the expected output and the actual output or error that you are seeing? RE: Loop of sums - MathFreak - Mar-20-2019 So when I do the math I find a=[1,3,2] if N=2 a=[1,6,11,6] if N=3 a=[1,10,35,50,24] if N=4 But my code shows a = [1, 10, 2] if N=2 a = [1, 42, 16, 3] if N=3 a = [1, 120, 60, 22, 4] if N=4 (I need to put the value of m equal to N to obtain all numbers of a, but that is not a problem because what we want is only a[m]) My main problem is that I have trouble translating so many sums into for loops. I just changed elif m>=1 btw, I didn't include the case if m=1. The code is now: def polynomial_with_roots(N, m): a = [0 for x in range (N+1)] mySum = [0 for y in range (N+1)] mySecondSum = [0 for z in range (N+1)] a[0]=1 if m==0: a[0]=1 elif N==1: a=[1,1] elif m>=1: # I changed it to 1 for i in range (1,m+1): print("i=",i) for kprevious in range (i,N+1): print("kprevious=",kprevious) for k in range (kprevious,N+1): print("k=",k) mySum[i]=mySum[i]+k print("mySum[i]",mySum[i]) mySecondSum[kprevious]=(kprevious-i+1)*mySum[i] a[i]=mySecondSum[kprevious] print("a[i]",a[i]) a[m]=a[i] print("a =",a) return a[m] polynomial_with_roots(2, 2) |