0

How to use the following code for recursion?

Want to implement do twice function code to recursion def add(x, y): return x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b))

6th Sep 2020, 9:40 AM
Harkeerat Pathak
Harkeerat Pathak - avatar
2 Answers
+ 3
Try this: total = [] count =0 def twice(x,y,c,t):    if c ==2:     return   else:     total.append(x+y)   twice(x,y,c+1,t)   twice(5,10,count,total) print(sum(total))
6th Sep 2020, 10:58 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
What you did is not really recursion. You should have a condition to stop and the recusive function call in your function. You could do this: def foo(func, x, y, i): if i==1: return func(x, y) temp = foo(func, x, y, i+1) return func(temp, temp) And call it with foo(add, 5, 10, 0)
6th Sep 2020, 9:51 AM
Jnn
Jnn - avatar