Search code examples
pythonarraysnumpyfunctioncomputation

Finding sum of a function u=n*x*y for n =[ 0 to N] ; x and y are some array


I want to write a code using python for solving a function such as follows :

u = sum(n*x*y) for n=[0 to N]

Let's say x = [1,2,3,4,5] and y =[6,7,8,9,10] and n= [1,2,..100]

I expect an output like this :

u = [u0, u1, u2, u3..]; where u0 = sum([nn*x[0]*y[0] for nn in n]) and similarly for u1,u2..

Thought of doing this :

u = []
For i in n:
    j = sum([i*x*y])
    u.append(j)

Now of course the problem I have is idk how I can go about defining x and y in the loop. Probably need to use another for loop or while loop, or some if/else, but I'm not able to wrap my mind around it for some reason. Pretty new to coding so any help would be appreciated.


Solution

  • I believe you want:

    uu = sum( nn*(sum(xx*yy) for xx,yy in zip(x,y)) for nn in n )
    

    which is similar but better than:

    uu = sum( nn*(sum(x[i]*y[i]) for i in range(len(x))) for nn in n )
    

    FOLLOWUP

    u = [sum([nn*xx*yy for nn in n]) for xx,yy in zip(x, y)]