2013-09-16 61 views
-3
def search_linear(x,y): 
    n = len(x) 
    for i in range(n): 

    if theValue[i] == y: 
     return True 

    return false 

def main(): 
    mainValues =int(input("enter the nos first")) 
    mV = mainValues.list() 

    trgt =int(input('enter a single number to be found in the list')) 
    def search_linear(mainValues, trgt) 

這是我寫的一個簡單的線性搜索程序。運行時,它在第17行上顯示invalid syntax,指向trgt = ...。 我不明白我出錯的地方。python的線性搜索

我寫了搜索功能,並在main函數中賦值。這樣一個簡單的程序

+0

除了不使用def,確保你的空白在語法上是正確的。 'return false'應該縮進到for循環的開始位置。 (我不知道這是否是一個錯誤,當複製在這裏或在您的實際程序) – Ross

+0

這是一個發佈錯誤,否則它會說'SyntaxError:'返回'外函數 –

+0

虛假應寫爲False。 var theValue在函數search_linear中是未知的。 mainValues.list()'int'對象沒有屬性'list'...從最後一個def search_linear(mainValues,trgt)中刪除def。 tbh它看起來像複製和粘貼沒有理解發生了什麼! –

回答

3

當你調用一個函數時,你不需要def。只需使用search_linear(mainValues, trgt)

def僅在您指定函數的定義時才需要。

-1
def LinearSearch(array, targetNumber): 
    for i in range (0,5): 
     array[i] == targetNumber: 
      print("The number %d does exist in the list." %(targetNumber)) 
     array[i] != targetNumber: 
      print("The number %d does not exist in the list." %(targetNumber)) 

import random 
random_number = [] 
for l in range (0,5): 
    random_number.append(random.randint(1,100)) 

# Algorithm Sort 
for i in range(0, 5): 
     for j in range (5-1, -1, -1): 
      if random_number[j] < random_number[j-1]: 
       new_value = random_number[j-1] 
       random_number[j-1] = random_number[j] 
       random_number[j] = new_value 
      if j == 1: 
       break 
0
#Tried my hand at a code by using simple keywords, no functions etc. Ideal for beginners. 
ls=[] 
n=input("Enter the number of elements in the list:") 
k=n-1 
for i in range(0,n,1): 
    b=raw_input("Enter the elements:") 
    ls.append(b) 
print ls 
element_to_be_searched=raw_input("Enter the element to be searched:") 
for j in range(0,k,1): 
    if ls[j]==element_to_be_searched: 
     if j+1==1: 
      print "Search is successful and requested element is the 1st element" 
      break 
     elif j+1==2: 
      print "Search is successful and requested element is the 2nd element" 
      break 
     elif j+1==3: 
      print "Search is successful and requested element is the 3rd element" 
      break 
     elif j+1>3: 
      print "Search is successful and requested element is the ",j+1,"th element" 
      break 
else: 
    print "Sorry,could not find the item you are looking for!" 

希望它可以幫助!