gpt4 book ai didi

python - 不使用 len 运算符查找列表的长度

转载 作者:太空宇宙 更新时间:2023-11-03 20:15:09 25 4
gpt4 key购买 nike

我必须编写 2 位代码来查找列表的长度,而无需使用 len 运算符,其中一位使用 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。”

最佳答案

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:])

关于python - 不使用 len 运算符查找列表的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com