简体   繁体   English

在不使用 len 的情况下使用递归 function 计算列表的元素数

[英]counting the number of elements of a list using recursive function without using len

I saw this code:我看到了这段代码:

def list_length(my_lis):
    if mylist:
        return 1 + list_length(my_lis[1:])
    return 0

This code counts the number of elements in the list recursively without using len function.此代码在不使用 len function 的情况下递归计算列表中的元素数。 Can someone please explain the list_length(my_lis[1:]) and how it gets added to 1 because from my understanding, my_lis[1:] gives the list without the first element.有人可以解释一下 list_length(my_lis[1:]) 以及它是如何添加到 1 的,因为据我了解,my_lis[1:] 给出的列表没有第一个元素。 So how can this give the number of elements in a list?那么这怎么能给出列表中元素的数量呢?

Ahh recursion, tends to make things more complex than they need to be, but it's still cool!啊递归,往往会使事情变得比他们需要的更复杂,但它仍然很酷!

Let's add some debug code to see what is happening让我们添加一些调试代码来看看发生了什么

def list_length(my_lis):
    if my_lis:
        print(my_lis)
        length = list_length(my_lis[1:])
        print(str(my_lis) + " returning 1 + " + str(length))
        return 1 + length 
    print("Empty List! Return 0")
    return 0

test_list = ['1', '2', '3', '4']

answer = list_length(test_list)

print("Answer: " + str(answer))

This will output:这将 output:

['1', '2', '3', '4']
['2', '3', '4']
['3', '4']
['4']
Empty List! Return 0
['4'] returning 1 + 0
['3', '4'] returning 1 + 1
['2', '3', '4'] returning 1 + 2
['1', '2', '3', '4'] returning 1 + 3
Answer: 4

Notice how we only reach the base case (return 0) after the list is empty.请注意,我们如何仅在列表为空后才到达基本情况(返回 0)。 Also notice that the number doesn't start going up until AFTER we hit the base case.还要注意,在我们达到基本情况之后,这个数字才会开始上升。 Only after we reach an empty list can we start going back up the chain and counting 1 + whatever the last function got.只有在我们到达一个空列表之后,我们才能开始返回链并计算 1 + 最后一个 function 得到的值。

Consider考虑

my_lis = [1,2,3]

if condition satisfies because list isn't empty so returns 1+list_length(my_lis[1:]) meaning my_lis[1:] means [2,3].如果条件满足,因为列表不为空,因此返回 1+list_length(my_lis[1:]) 表示 my_lis[1:] 表示 [2,3]。 So to generalize it you are decreasing length of list by one, that is you count the first element and ignore the first element.因此,概括地说,您将列表的长度减少一个,即您计算第一个元素并忽略第一个元素。

return 1+ list_length(my_lis[1:])            #my_lis=[2,3]
return 1+ 1+ list_length(my_lis[1:])         #my_lis=[3]
return 1+ 1+ 1+ list_length(my_lis[1:])      #my_lis=[]
return 1+ 1+ 1+ 0

This goes as follows:这如下:

  • If my_lis is not falsy (assumes non-empty list)如果my_lis不是假的(假设非空列表)
  • Return 1 + call the same func on a list of the next item until the last返回 1 + 在下一项的列表上调用相同的函数,直到最后一项
  • If this new list is not falsy如果这个新列表不是假的
  • Return 1 + call the same func on a list of the next item until the last返回 1 + 在下一项的列表上调用相同的函数,直到最后一项
  • ... ...

This goes on until my_lis[1:] returns None, in this case instead of returning 1 we will return 0 and we do not trigger another recursive call.这一直持续到my_lis[1:]返回 None,在这种情况下,我们将返回 0 而不是返回 1,并且不会触发另一个递归调用。

Going from the innermost instead:从最里面开始:

  • my_lis is empty, return 0 my_lis为空, return 0
  • my_lis is not empty, return 1 + 0 my_lis不为空, return 1 + 0
  • my_lis is not empty, return 1 + (1 + 0) my_lis不为空, return 1 + (1 + 0)
  • my_lis is not empty, return 1 + (1 + 1 + 0) my_lis不为空, return 1 + (1 + 1 + 0)
  • ... ...

This is how you end up with a list length.这就是您最终获得列表长度的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM