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?
Easy solution to get a sum of a list is to use sum()
function, eg list_sum = sum([1, 2, 3])
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.
arr
points to [1,2,3]
arr
points to [2,3]
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
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'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.