'Product' Exercise code failing skipping first index!


#1

def product(n):
for i in range(len(n)-1):
product = n[i] * n[i+1]
return product

I do not understand why this code is not properly computing the product. I am getting "Your function fails on product([4, 5, 5]). It returns 25 when it should return 100." Why is the first index of the list being skipped (i.e., returning 25)?


#3

Your loop overwrites "product" in every iteration.

if i=0 you set product to 4 * 5
if I=1 you set product to 5 * 5
and there it breaks because of range(len(n)-1) => (from 0 to 1)

so the result is 25. Effectively your code multiplies the last two entries of any given list.

to fix it you need to reuse the result of each iteration within the next iteration.

Suggestion:
def product(n):
. product = 1
. for i in n:
. product = product * i
return product


#4

i did the same as like your your suggestion , but i don't know where did i went wrong ..

def product(integers):
total = 2
for num in integers:
total = total * num
return total


#5

Your total should equal 1 not 2:

def product(int_lst):
total = 1
for i in int_lst:
total = total * i
return total


#6

try this:

def product(numbers):
result = 0
for number in numbers:
if result==0:
result = number
else:
result = result * number

return result

#7
def product(lista):
    res =1
    for x in lista:
        if x != 0:
            res *= abs(x)
    return int(res)

product([-4, 5, 70, -20])indent preformatted text by 4 spaces