Python 替代Len函数
我正在写一个简单的搜索算法。下面是我的代码Python 替代Len函数,python,function,Python,Function,我正在写一个简单的搜索算法。下面是我的代码 def search(list_data,target_char): found = False position = 0 while position < len(list_data) and not found: if list_data[position] == target_char: found = True position += 1 return f
def search(list_data,target_char):
found = False
position = 0
while position < len(list_data) and not found:
if list_data[position] == target_char:
found = True
position += 1
return found
def搜索(列出数据、目标字符):
发现=错误
位置=0
当位置
但是,我不应该使用len()或任何其他内置函数。我该怎么做呢?正如我在评论中所写的那样,您可以使用
while True
并在找到要查找的内容或用尽列表时手动终止它
def search(list_data, target_char):
found = False
position = 0
while True:
try:
if list_data[position] == target_char:
found = True
break
except IndexError:
break
position += 1
return found
print(search([1, 3, 5], 3)) # prints: True
print(search([1, 3, 5], 'asdas')) # prints: False
您可以自己创建len函数,如下所示:
def myLen(tab):
index = 0
while(tab != []):
tab = tab[0:-1]
index+=1
return index
为True时:。。。中断
?您还需要像您一样手动增加位置,并使用try-except
块捕获索引器
a=[1,3,4,5]
print(myLen(a))