13. product where is my mistake?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/3?curriculum_id=4f89dab3d788890003000096#


returns 400 when it should return 100


def product(numbers):
    result = numbers[0]
    for number in numbers:
        if number != 0:
            result *= number
        elif number == 0:
            result == 0
            break
    return result


#2

As products go, zero is a factor that we would not wish to exclude. If there is a zero in the list, it should be allowed to apply, then break and return. The construct would be a variation on what you have (which is sort of overkill, btw)...

def product(numbers):
    result = 1    # force a non-zero unity preset
    for number in numbers:
        result *= number
        if result == 0:
            break
    return result
    
print product([2,4,6,8,9])    # 3456
print product([2,4,0,6,8])    # 0

#3

Hey! thanks for the quick response :slight_smile:
It appears that the bug was result = number[0], trying to figure out why but now it works !
I actually did exactly what you wrote which didn't work as a result of what I wrote above which made me go insane and "overkill" lol


#4

Yeah, when that happens it is a sure sign we can do better, but need to step away for a minute, or start over from scratch. What always throws me is working out the perfect algo (in my own mind) only to see a refactored form that puts it to shame. Never be hard on yourself for putting in an honest effort. How else would we be able to spot the jewels when we come across them?

def product(n)
    return reduce(lambda x, y: x * y, n)

z = [2,4,6,8,9]
print product(z)    # 3456