python中reduce实现阶乘

  1. from functools import reduce
  2. def prod(L):
  3. def myCheng(x,y):
  4. return x*y
  5. return reduce(myCheng,L)
  6. print( "3*5*7*9=",prod([ 3, 5, 7, 9]))

或者用lambda函数进一步简化成:

  1. def prod(L):
  2. return reduce( lambda x,y:x*y,L)
  3. print( "3*5*7*9=",prod([ 3, 5, 7, 9]))

你可能感兴趣的:(python中reduce实现阶乘)