+ 2
def sum (a,b): if a == 0 or b == 0: return 0
hei guys, can someone clarify the logic behind this code please? Despite trying different arguments, I've not quite gotten my head around it. The output is : 3 def sum (a,b): if a == 0 or b == 0: return 0 return 1 + sum(a-1, b-1) print(sum(7, 3))
5 odpowiedzi
+ 4
sum(4, 0) = 0
sum(5, 1) = 1 + sum(4, 0) = 1 + 0 = 1
sum(6, 2) = 1 + sum(5, 1) = 1 + 1 = 2
sum(7, 3) = 1 + sum(6, 2) = 1 + 2 = 3
+ 3
Eren Kılıçlar the logic is ,
The func sum is called and checks since it is 7 and 3 so else statement exists so 1 is returned. again sum(7-1,3-1) calls again else statement so return 1
Like wise it works till b becomes 0 so answer is 3
+ 3
Visualize your code execution
(Python, Java, C, C++, JavaScript, Ruby)
https://pythontutor.com
+ 1
because the recursion is happening only 4 times so:
1+1+1+0
it's because the function returns 0 when either 7 or 3 become 0
with every recursion both 7 and 3 are decreased by 1
so 3 becomes 0 first which results in end of recursion by returning 0
+ 1
Thanks guys, just applied your breakdowns using different arguments. Makes sense now.