0
I don't actually understand what is happening here.
You see the code below, I want to know what does the 'return' statement actually returns and to where? Is [3,4,2,5] the value of calc(list[1:]) and does it change or not? 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) o
1 Resposta
+ 1
If you just call calc like this
list = [1, 2, 3]
calc(list)
the return goes to nowhere.
You can save it into a variable like in your postet code.
x = calc(list)
clalc returns 0 if the list is empty.
If not this happens:
1. It takes the first value from list and squares it.
2. Takes a the rest from the list and calls calc with it again.
This happens so long till there is no rest, so the given list is empty.
If you input was [1,2,3] the result is 14.
calc([1,2,3]) # 14
1*1 + calc([2,3]) # 1 + 13
2*2 + calc([3]) # 4 + 9
3*3 + calc([]) # 9
0