簡體   English   中英

詢問用戶5個數字,並顯示一條消息,說明該數字是否在列表中

[英]Ask the user for 5 numbers and display a message saying whether the number was on the list or not

我正在嘗試編寫一個程序,該程序創建一個隨機列表,對該列表進行排序,然后向用戶詢問5個數字,並使用二進制搜索顯示消息該數字是否在列表中。 我收到錯誤消息BubbleSort(ran_list) Type Error:ran_list not defined 任何幫助將是有益的,我還以為ran_list在明確createList功能。

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")

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

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

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")

將代碼的第一行更改為:

ran_list = createList()

另外,您應該將import random放在腳本的頂部

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM