问题
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
回答1:
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 of product
and return it unchanged.
def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product
回答2:
One way of doing this is using the reduce()
function from functools
and the operator.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 number i
is even, the value i % 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.
import functools, operator
def even_product(lst):
return functools.reduce(operator.mul, [i for i in lst if i%2 == 0], 1)
回答3:
This will be your answer:
def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product
There is no need to return
1
since the product is already assigned 1
.
Since you has the return
inside the for
loop it was returning the value after identifying the first even number. Hope it helped.
来源:https://stackoverflow.com/questions/39835536/python-multiplying-all-even-numbers-in-a-list