+ 1
Explanation of Fun With Math quiz
I can't understand what happen after i do the exponential of the first element of the list(index 0): else: return list[0]**2 + calc(list[1:]) This is the solution code of the quitz: def calc(list): if len(list)==0: return 0 else: return list[0]**2 + calc(list[1:]) list = [1, 3, 4, 2, 5] x = calc(list) print(x)
3 Respuestas
+ 3
It recursively calling calc() function with list as
1st call : list => [ 1,3,4,2,5 ]
2nd call : list[1:] => [ 3,4,2,5 ]
3rd call : list[1:] => [ 4,2,5 ]
4th call : list[1:] => [ 2,5 ]
5th call : list[1:] => [ 5 ]
In next call [ ] length is 0 so it stop recursion.
In all calls, it finding list[0]**2
So
It returns
1**2 + 3**2 + 4**2 + 2**2 + 5**2
Hope it helps..
+ 2
Matteo Passone Side note: don't use reserved words like "list" as variable names. You replaced a full class (list), with its methods, for another object. This can give you headaches.
+ 1
Okay, pretty clear, thanks you