Fawcett Fawcett
Fawcett Fawcett

Reputation: 47

Modify python code to return the product of the items on the list rather than the sum

Can anyone help to modify this small block of code i have to return the product of the items on the list rather than the sum.

This is the code:

def sum(seq):

    def add(x,y): return x+y

    return reduce(add, seq, 0)

Upvotes: 0

Views: 139

Answers (2)

laundmo
laundmo

Reputation: 338

since youre already using reduce, just modify the function reduce uses:

def product(seq):
    def mult(x, y): return x * y
    return reduce(mult, seq)

alternatively use a lambda instead of a function definition:

reduce(lambda x,y: x*y, seq)

btw, for sum python has the builtin function sum: https://docs.python.org/3/library/functions.html#sum

Upvotes: 1

Prashant Kumar
Prashant Kumar

Reputation: 2092

I think I understood your problem. Try this :

import functools
import operator
def multiplyList(inputList):
    return(reduce(operator.mul, inputList))

Upvotes: 1

Related Questions