0

Why the Output gives 3?

def fun(a,p=0): if(p==len(a)): return 0 z=1 if not a[p] else 0 return z + fun(a,p+1) a=[1,0,1,1,0,1,0] print(fun(a))

13th Jul 2021, 5:06 PM
Moon
Moon - avatar
5 Respuestas
+ 4
Mahmuda Akter Moon We are counting 0 so here total number of 0 is 3 in list See this line z = 1 if not a[p] else 0 Here if not 1 menas 0 then count is 1 otherwise count is 0 so there is total number of 0 is 3
13th Jul 2021, 5:18 PM
A͢J
A͢J - avatar
+ 2
The function fun will be recursed until the variable 'p' equals 7. During this, the value of the variable 'z' will change to 0 or 1 depending on the values ​​of the array 'a' (if a[p]==1: z=0 else z=1) As a result of execution of 5, the line will look like this: "return 0+1+0+0+1+0+1"
13th Jul 2021, 5:55 PM
Solo
Solo - avatar
+ 1
z=1 if not a[p] else 0 flips 0 to 1 and 1 to zero. p+1 in every recursion p becomes +1 greater until the end of the list a and there becomes 0 again. recursion break. and if to flip 0 to 1 and 1 to zero here will be 3 ones in a list. so in the end z = 1+1+1==3 or in short: z = 0+1+0+0+1+0+1
13th Jul 2021, 5:28 PM
Shadoff
Shadoff - avatar
+ 1
Mahmuda Akter Moon In 5th line we are adding count like: 0 + 1 + 0 + 0 + 1 + 0 + 1 = 3 That is recursion. We are calling function and incrementing p and checking next value to count 0 till p == len(a)
13th Jul 2021, 5:40 PM
A͢J
A͢J - avatar
0
What about the 5th line?
13th Jul 2021, 5:28 PM
Moon
Moon - avatar