Home > Mobile >  How list slicing works for finding sum of element by using recursion
How list slicing works for finding sum of element by using recursion

Time:09-26

def s(arr):
    if len(arr) == 1:
        return arr[0]

    return arr[0]   s(arr[1:])

Above code is to find the sum of a list using recursion. So when I call the function again by giving a slicing list isn't the length of the list always gonna be same after every recursion call? Then how is my base condition is satisfying?

CodePudding user response:

Easy solution to get a sum of a list is to use sum() function, e.g. list_sum = sum([1, 2, 3])

CodePudding user response:

At every iteration, your method s calls recursively itself on a shrinked version of the arr parameter: this is done at s(arr[1:]) statement.

  1. First call: arr points to [1,2,3]
  2. Second call: arr points to [2,3]
  3. Third call: arr points to [3]

At this point, since len([3]) == 1, the case base guard is satisfied and the return value is 3 and so on recursively, popping one activation record at time from the stack (LIFO).

A demo here: demo

CodePudding user response:

When you slice a list, it creates a new list, typically with a smaller number of elements.

You can verify it easily by using print to examine the lists:

def print_indexed_list(l):
    print(dict(enumerate(l)))

arr = ['a', 'b', 'c', 'd', 'e']

print_indexed_list(arr)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

print_indexed_list(arr[1:])
{0: 'b', 1: 'c', 2: 'd', 3: 'e'}

print_indexed_list(arr[:4])
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

print_indexed_list(arr[1:3])
{0: 'b', 1: 'c'}

print_indexed_list(arr[::2])
{0: 'a', 1: 'c', 2: 'e'}
  • Related