I come to this point when I was making a simple calculator. I did a simple program to sum the list of numbers as follows, But the program for multiplication is a little bit long.
So can anybody have any idea how to make short program to multiple list of numbers in python. Here is my code what looks like.
def calculate(oper,*nm):
return oper(nm)
add=lambda x:sum(x)
def mult(lst):
tmp=1
for i in lst:
tmp*=i
return tmp
calculate(add,2,34,2)
calculate(mult,8,5,7)
Really, you do not need to define
calculatebecause Python already has a name for it: reduce.Note: In Python3,
reducehas been moved to the functools module. (Thanks to @ErikRoper for pointing this out.)