2017-01-22 162 views
-3

該函數搜索數組中元素的數量,並返回數組中元素的數量(如果該數組存在),或者返回-1(如果數組中不存在輸入數字)將C函數轉換爲Python函數

int iSearch (int st[],int len,int no) 
{ 
    int i; 
    for (i=1;i<=len;i++) //len=lenth of the array , no = the number that we want to search in the array , st[] = the array 
     if (st[i]==no) 
      return i; 
     return -1; 
} 

我想寫這個函數的python版本,但由於我在Python中使用列表而不是數組,我不知道如何在python中編寫它。

我寫了下面的代碼在python,但它不工作

def iSearch(list,lenth,no): 
    x=0 
    for x in range (lenth): 
     if (list(x) == no) 
      return i 
     else 
      return -1 
+1

你不需要有長度! –

+0

你正在使用哪個版本的python? –

+0

即時通訊使用python 3.6 –

回答

3

這裏的循環相當於:

def iSearch(lst,no): 
    for i,x in enumerate(lst): 
    if x == no: 
     return i 
    return -1 

有,但是,功能lst.index(no)這是做你需要什麼,但以更有效的方式:

def iSearch(lst,no): 
    if no in lst: 
    return lst.index(no) 
    return -1 

或與try/except(可能是最快的):

def iSearch(lst,no): 
    try: 
    return lst.index(no) 
    except ValueError: 
    return -1 
+1

'index'需要'try/except'塊BTW –

+0

@ Jean-FrançoisFabre正確。 – DyZ

+1

gotcha:我已經upvoted :),你不必爲我糟糕的答案可能下調而感到不好。我不認爲它是個人的,不像那些在你決定一個問題時連續低估你的bozos。這裏不需要' –

1

這將幫助,如果你提供你有下一次的錯誤。

你的代碼有一些問題:1.「list」是一個已經存在的對象的名字2.你只是檢查第一個項目是否是所需的對象,因爲那時兩個分支都返回。 3.訪問列表元素需要方括號,而不是括號。

這似乎工作:

def linear_search_c(l,length,num):                              
    for x in range(0,length):             
    if (l[x] == num):              
     return x                
    return -1 

順便說一句,有更好的搜索列表比線性搜索方法,如果數組進行排序:binary search

+1

'x = 0'。和FYI的排序數組,你可以使用'bisect' python模塊。 –

+0

謝謝法布爾,很高興知道對分。 –