I
I
Ilkhomjon Matazimov2020-07-02 07:53:49
Python
Ilkhomjon Matazimov, 2020-07-02 07:53:49

How to write a recursive function to count elements in a list?

There is a list: . We need a recursive function to calculate the sum of all these elements. It's easy to do this through a loop:[1, 2, 3, 4]

def sum_el(arr):
    total = 0
    for x in arr:
        total += x
    return total


print(sum_el([1, 2, 3, 4]))
# 10

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilhomjon Matazimov, 2020-07-02
@mr_qpdb

def recursion_sum(arr):
    if not arr:
        return 0
    return arr[0] + recursion_sum(arr[1:])

D
Dr. Bacon, 2020-07-02
@bacon

1. the task can be googled without problems, so learn this "python recursive list sum"
2. here is the template, homework to add it

def recursion_sum(els):
    el, *tail = els
    return el + recursion_sum(tail)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question