2017-04-21 88 views
0

我在写一个简单的搜索算法。以下是我的代码。替代Len函数

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 

但是我不应该使用len()或任何其他内置函数。我怎么能这样做?

+0

'而真实:... break'?你还需要像你一样手动增加位置,并且需要一个'try-except'块来捕捉'IndexError' –

回答

0

正如我在评论中写的那样,您可以使用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 
+0

类型的先生,非常感谢你 –

1

也许只是创建自己的len函数,像这样的东西:

def myLen(tab): 
    index = 0 
    while(tab != []): 
     tab = tab[0:-1] 
     index+=1 
    return index 

a=[1,3,4,5] 
print(myLen(a))