-1

I am trying to multiply each element with the one next to it, and then sum them together. ( I have to use a for/while loop since this is what is required for the question i am trying to solve)

C= [7,5,4,5,3]
j = 0
for j in len(C):
    j += 1
    answ = (int(C[0::j])*int(C[1::j]))
print answ

I keep getting the error message "int object not iterable" I would appreciate if someone could help me with this.

Heba Masarwa
  • 57
  • 1
  • 7
  • 1
    what would be the desired outcome for the example list you provided? – Ma0 Nov 12 '18 at 14:46
  • 1
    you are iterating over ```len(C)``` which is a number you should write : ```for j in C``` instead. – NaWeeD Nov 12 '18 at 14:46
  • the problem with your code is that you are trying to convert a list to int with `int(C[0::j])`. Do you understand how *slicing* works? – Ma0 Nov 12 '18 at 14:47
  • the outcome will be 90. and while i do understand the basics for slicing the program wasn't cooperation, so i started trying random things and this is what i ended up with. – Heba Masarwa Nov 12 '18 at 14:51
  • You're looking for a [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator). Using `window` from those answers, do `sum((x*y) for x, y in window(C))` – Patrick Haugh Nov 12 '18 at 14:54

2 Answers2

3

You could zip() through list, multiplying items and taking sum() at the end:

C = [7,5,4,5,3]
print(sum(x * y for x, y in zip(C, C[1:])))
# 90
Austin
  • 25,759
  • 4
  • 25
  • 48
  • thank you so much! but if it isn't too much trouble can i ask you what exactly is zip? i am new to coding and i really want to understand the material better. sorry for your trouble! – Heba Masarwa Nov 12 '18 at 14:59
1

There's a number of issues with your approach. First, you're attempting to iterate over the value len(C) in your for-loop. Instead, you'd want to use range(len(C)) as this returns a generator of integers from 0 to len(C), which you can iterate over. Second, we don't make changes to loop variables in Python because the variable is overwritten at the start of every iteration of the loop so any changes would be ignored. Third, your calculation of answ will yield errors because you're trying to cast array slices to integers. You're also indexing them backwards. What you want to do is:

sum(a * b for a, b in zip(C, C[1:]))

This will get you a sum of the multiplication of every element in the list with the element in the position to the right of it. This doesn't consider the edge of the list however.

Woody1193
  • 7,252
  • 5
  • 40
  • 90