0

Change the code to get the sum of squares of the list items recursively

We have a function that returns sum of list elements using recursion. So now, we have change the code to output the sum of the squares of all the list items.. Имеется функция, возвращающая сумму элементов списка рекурсивным способом. Теперь нужно переделать код, чтобы получить сумму квадратов элементов списка. def calc(list): if len(list)==0: return 0 else: return list[0] + calc(list[1:]) list = [1, 3, 4, 2, 5] x = calc(list) print(x) I tried adding loop for to iterate over the elements of the list and create a new list, where I will add new elements. The question is how to do this recursively correctly. Я попробовал добавить цикл for чтобы перебрать элементы списка и создать новый список, куда добавлю новые элементы. Вопрос в том, как правильно выполнить это рекурсивно. newList[] for i in list: n = i**2 newList.append(n)

11th Jul 2021, 10:55 AM
Plateau Born
Plateau Born - avatar
6 Answers
+ 5
Change the return list[0] in calc function to list[0]**2 !
11th Jul 2021, 11:05 AM
Abhay
Abhay - avatar
+ 3
Plateau Born Here's a one-liner: calc = lambda x: x[0] ** 2 + calc(x[1:]) if x else 0 # Hope this helps
11th Jul 2021, 4:25 PM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Plateau Born list[0] will take 1st value from list and after each iteration list[1:] will change like [3, 4, 2, 5] [4, 2, 5] [2, 5] [5] And finally []
11th Jul 2021, 12:02 PM
A͢J
A͢J - avatar
+ 1
Thanks! now it comes, the whole trick is that the function calls itself
11th Jul 2021, 12:25 PM
Plateau Born
Plateau Born - avatar
0
Abhay, but how does it work??? I can't understand correctly, list[0] takes the values ​​of the list in order???
11th Jul 2021, 11:20 AM
Plateau Born
Plateau Born - avatar
0
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)
7th Sep 2023, 4:37 AM
Ares TM
Ares TM - avatar