Home > other >  Python function recursive problem
Python function recursive problem

Time:11-27

Continuous multiplication function, I want to write a reference for the addition of recursion, the return statement of "+" is replaced by "*", but the result is 0,
How to write to achieve the purpose of multiplication? (1 * 2 * 5 * 9), thank you

Def mysum (l) :
Print (l)
If not l:
Return 0
The else:
Return [0] * mysum l (l [1])
Print (mysum (,2,5,9 [1]))

Code execution results:
[1, 2, 5, 9]
[2, 5, 9]
[5, 9]
[9]
[]
0

CodePudding user response:

Now that is the multiplication, there will be no return 0, finally to return 1

 

Def mysum (l) :
Print (l)
If not l:
Return 1
The else:
Return [0] * mysum l (l [1])
Print (mysum (,2,5,9 [1]))

CodePudding user response:

 the from functools import reduce 
Def f (ls) :
Return the reduce (lambda x, y, x * y, ls)
Print (f (,2,5,9 [1]))
  • Related