13. product


Well, this activity is difficult. I am stuck again and I can't seem to find anyone else who has this problem. D: Link: https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/3?curriculum_id=4f89dab3d788890003000096#

It gives me this error message: Oops, try again. Your code looks a bit off--it threw a "list index out of range" error. Check the Hint if you need help!

I expect it to return i as an interger.

def product(x):
    y = 0
    z = x
    for i in x:
        if y < len(z):
            i = z[y]
            i *= z[y+1]
            y += 1
            return i

Note: I did z because i thought that if i did x x won't really be a variable, but just an argument and it would be [ , , ] so example: [1,2,3][y+1] won't work.
I might be wrong though.
Thanks in advance.


but your for loop will give you all the values of the list:

def product(x):
    for i in x:
         print i
print product([4, 5, 5])

so why also use z? its not necessary, in fact, it massively complicate things.

now declare a variable total before the loop, give it a value of 1. Now multiply total with all values of i to get the product


There's your error type, and there is your mistake.

Note: Because x is a reference object it is not copied over to z, which is just another pointer to the same object. To make a discrete copy of a list, take a slice.

z = x[:]

What if we just cut to the chase and chew through the duplicate list, destruction of which has no bearing on the original...

    p = 1
    while len(z):
        p *= z.pop()
    return p

print (product([1,2,3,4,5,6,7])    # 5040



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.