询问用户5个号码并显示一条消息,说明该号码是否在列表中

时间:2017-04-22 20:07:38

标签: python

我正在尝试编写一个创建随机列表的程序,对该列表进行排序,然后向用户询问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")

3 个答案:

答案 0 :(得分:1)

当您尝试将其传递到ran_list时,未定义

myBubbleSort()。将主程序的第一行更改为ran_list = createList()

答案 1 :(得分: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")

答案 2 :(得分:0)

将代码的第一行更改为:

import random

此外,您应该将.carousel-wrapper放在脚本的顶部