[英]How list slicing works for finding sum of element by using recursion
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?
因此,当我通过提供切片列表再次调用 function 时,每次递归调用后列表的长度是否总是相同? 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])
获得列表总和的简单解决方案是使用
sum()
function,例如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.在每次迭代中,您的方法
s
在arr
参数的缩小版本上递归调用自身:这是在s(arr[1:])
语句中完成的。
arr
points to [1,2,3]
arr
指向[1,2,3]
arr
points to [2,3]
arr
指向[2,3]
arr
points to [3]
arr
指向[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).此时,由于
len([3]) == 1
,满足 case base 保护并且递归返回值为3
等等,从堆栈(LIFO)中弹出一个激活记录。
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:您可以通过使用
print
检查列表来轻松验证它:
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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.