0

So I have a list that has numbers like [1,2,3,4,5]. What I need the code to be able to multiply and add the numbers so it would look like 1*5 + 2*4 + 3*3 + 4*2 + 5*1. Although these numbers can change based on user input, so it can also look like [1,2,3,4] (1*4+2*3+3*2+4*1)

Also, I'm only allowed to use the operations of the length of list, list accessor, create an empty list, List append.

AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33

2 Answers2

1

If you want the result to be stored in a variable, you could do this:

y=[1,2,3,4,5]
s=len(y)
x=0 #initialize result to 0
for i in range(s):
    x = x + (y[i]*y[s-1-i]) 
    #y[s-1-i] is the the element to be multiplied with y[i]
print(x)
Sai
  • 109
  • 8
0
x=[1,2,3,4,5]
total_sum=sum([a*b for a,b in  zip(x,x[::-1])])

Note: x[::-1] reverses the list

Mehul Gupta
  • 1,829
  • 3
  • 17
  • 33