0
Can someone help me with this
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)
6 Answers
+ 2
This function is a recursive function, means it calls itself.
if len(list) == 0:
return 0
This part is the end condition.
Now to the else part:
return list[0]**2 + calc(list[1:])
the first part is just the first element of your list ^ 2
The second part calls calc() but without the first element (using list slicing)
1. l = [1,3,4,2,5]
1^2 + calc([3,4,2,5])
2. l = [3,4,2,5]
3^2 + calc([4,2,5])
3. l = [4,2,5]
4^2 + calc([2,5])
4. l = [2,5]
2^2 + calc([5])
5. l = [5]
5^2 + calc([])
6. l = []
the list is empty here you just return 0
Each method call returns a value:
6. returns 0
5. returns 25 + 0 (value from 6.)
4. returns 9 + 25 (value from 5.) = 34
3. returns 16 + 34(value from 4.) = 50
2. returns 4 + 50 (value from 3.) = 54
1. returns 1 + 54 (value from 2.) = 55
So at the end the function returns 55.
+ 2
Hello David Lahu
In your code you get 1^2 + 3^ + ... + 5^ = 55
Is this not what you want to do or do you want to know how it works?
Please share more details about your problem.
0
I would like to know how it works Denise
0
Thanks
0
Hello:
I had reviewed and run this code but always says : Error indent at line 3. Please help. Thanks in advance.
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)
0
Hello:
I had reviewed and run this code but always says : Error indent at line 3. Please help. Thanks in advance.
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)
@Felix A. Vargas A.
The return statement should have an indentation since it's a statement under the 'if' conditional. The else and if are supposed to be on the same line instead of the return. It shows an error because nothing under the return ever gets run(Unless it's not directly related to it). Hope this helps