Can someone help me with this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

26th Jan 2022, 5:00 PM
David Lahu
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.
27th Jan 2022, 6:16 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
26th Jan 2022, 5:11 PM
Denise Roßberg
Denise Roßberg - avatar
0
I would like to know how it works Denise
27th Jan 2022, 5:06 PM
David Lahu
0
Thanks
30th Mar 2022, 11:53 PM
David Lahu
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)
2nd Oct 2022, 11:35 AM
Felix A. Vargas A.
Felix A. Vargas A. - avatar
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
19th Jun 2023, 9:40 AM
David Lahu