【问题标题】:Finding the length of a list without using the len operator [duplicate]在不使用 len 运算符的情况下查找列表的长度 [重复]
【发布时间】:2019-10-22 11:55:02
【问题描述】:

在不使用 len 运算符的情况下,我必须编写 2 位代码来查找列表的长度,一位使用 for 循环,另一位使用递归。我的递归片段有问题。

def list_length(list):
    sum=0
    if not list:
        print("The list is empty.")
        exit()
    if type(list) == type([]):
        for item in (list):
            sum+=1
        print("The length of the list is ",sum)

    else:
        print("The input is not a list.")
        exit()

my_list = [1,12,15,100];
list_length(my_list)



def recursive_length(list):
    sum=0
    if not list:
        print("The list is empty.")
        exit()
    if type(list) == type([]):
        if list:
            return 1 + recursive_length(list[1:])
            return 0
        print("The length of the list is ",sum)

    else:
        print("The input is not a list.")
        exit()

my_list = [13,12,1];
recursive_length(my_list)

第一种方法按预期工作,但对于我的递归方法,输出是“列表为空。”,我应该得到“列表的长度是 3。”

【问题讨论】:

  • sum([1 for item in mylist]) 有什么问题? :-)
  • 递归解决方案最终总是会收到一个空列表。这是预期的。这被称为递归的“基本情况”。在这种情况下不要退出。想想应该在基本情况下返回什么。

标签: python


【解决方案1】:
def recursive_length(my_list):
    if not isinstance(my_list, list):
        raise ValueError("I can only determine the length of a list, sorry.")
    if not my_list:
        return 0

    return 1 + recursive_length(my_list[1:])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多