2017-04-21 116 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))