2017-04-22 34 views
0

我正在嘗試編寫一個程序,該程序創建一個隨機列表,對該列表進行排序,然後詢問用戶5個號碼並使用二進制搜索以顯示消息號碼是否在列表中。我收到錯誤消息BubbleSort(ran_list) Type Error:ran_list not defined。任何幫助將有所幫助,我認爲ran_list明確定義在createList函數中。詢問用戶5個號碼,並顯示一條消息,說明號碼是否在列表中

def createList(): 
    import random 
    ran_list=[] 

    for n in range(50): 
     numbers=random.randint(1,100) 
     ran_list.append(numbers) 

    return ran_list 

def myBubbleSort(ran_list): 
    for i in range(len(ran_list),0,-1): 
     for j in range(0,i-1): 
      if ran_list[j]>ran_list[j+1]: 
       temp=ran_list[j] 
       ran_list[j]=ran_list[j+1] 
       ran_list[j+1]=temp 

    return ran_list 

def myBinarySearch(value,ran_list): 
    low=0 
    high=len(ran_list)-1 
    pos=-1 

    while low<=high and pos==-1: 
     mid=(low+high)//2 

     if ran_list[mid]<value: 
      low=mid+1 

     elif ran_list[mid]>value: 
      high=mid-1 
     else: 
      pos=mid 

    return pos 

'' ' 主程序 '''

createList() 
myBubbleSort(ran_list) 

for i in range(5): 
    value=int(input("Please enter a number: ")) 
    myBinarySearch(value,num_list) 

    if pos==-1: 
     print("The number is not in the list") 

    else: 
     print("The number is in the list") 
+0

您還沒有定義'ran_list'在你的主程序中。 –

回答

1

ran_list當你嘗試將其傳遞到myBubbleSort()沒有定義。將主程序的第一行更改爲ran_list = createList()

1

你忘了在代碼中定義許多變量。這是你的編輯代碼:

def createList(): 
    import random 
    ran_list=[] 

    for n in range(50): 
     numbers=random.randint(1,100) 
     ran_list.append(numbers) 

    return ran_list 

def myBubbleSort(ran_list): 
    for i in range(len(ran_list),0,-1): 
     for j in range(0,i-1): 
      if ran_list[j]>ran_list[j+1]: 
       temp=ran_list[j] 
       ran_list[j]=ran_list[j+1] 
       ran_list[j+1]=temp 

    return ran_list 

def myBinarySearch(value,ran_list): 
    low=0 
    high=len(ran_list)-1 
    pos=-1 

    while low<=high and pos==-1: 
     mid=(low+high)//2 

     if ran_list[mid]<value: 
      low=mid+1 

     elif ran_list[mid]>value: 
      high=mid-1 
     else: 
      pos=mid 

    return pos 



ran_list = createList()        # Was not assigned to ran_list 
num_list = myBubbleSort(ran_list)      # Same here.. 

for i in range(5): 
    value=int(input("Please enter a number: "))  
    pos = myBinarySearch(value,num_list)    # Was not assigned 

    if pos==-1: 
     print("The number is not in the list") 

    else: 
     print("The number is in the list") 
+0

感謝您的幫助 –

0

更改代碼的第一行:

ran_list = createList() 

你也應該把import random在腳本的頂部

+0

謝謝你的幫助,但我很困惑。如何通過第一行代碼執行ran_list = createList(),在定義它之前我無法調用函數。 –

+0

我的意思是你的主要劇本。你也應該參考@direnprobs解決方案。它好得多,並解決了所有問題 – Kev1n91

相關問題