I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?
def evens_product(xs):
product = 2
for i in xs:
if i%2 == 0:
product *= i
return product
else:
return (1)
Edit: Chepner's solution worked thank you to everyone who helped
You need to initialize
product = 1
, for two reasons. One, simply put, you'll get the wrong answer.evens_product([4])
should return 4, not 8. Two, it saves you from having to treat a list with no even numbers as a special case. If there are no even numbers, you never change the value ofproduct
and return it unchanged.This will be your answer:
There is no need to
return
1
since the product is already assigned1
. Since you has thereturn
inside thefor
loop it was returning the value after identifying the first even number. Hope it helped.One way of doing this is using the
reduce()
function fromfunctools
and theoperator.mul()
function.The
reduce()
function takes a function that takes three arguments (in this case,operator.mul()
), an iterable (which is a list in this case), and default value.It applies the function to the first two elements, yielding a result. It takes that result, and applies that function to the result and the third element of the list, then the result of that to the fourth and so on. It repeats this process until all arguments have been iterated through.
In this case, operator.mul() is used to describe the multiplication operation. For example,
operator.mul(2,3)
is 6.Lastly, you can select even values in a list by using a list comprehension with an
if
clause at the end. If a numberi
is even, the valuei % 2
should be zero, since%
is the modulus operator, which returns the remainder after the left side is divided by the right.Here is what an implementation would look like, although you should define behavior for when there are no even numbers, perhaps with
try: except:
blocks.Added default/initial value
1
to avoid error in case of empty list.