TypeError:+:'int'和'list'的不支持的操作数类型

时间:2017-03-03 10:15:48

标签: python list int

我的二进制搜索功能代码一直出现此错误

ex = [3, 4, 19, 42, 53, 23, 5, 8, 20] #list used
number = input("What number do you want to find?: ")
length = len(ex) - 1
first = 0
last = [len(ex)]
done = False
while done == False:
    for i in range(length):
        if ex[i] > ex[i+1]:
            sort = False
            ex[i], ex[i+1] = ex[i+1], ex[i] #flips the numbers in the list
        else:
            print (ex)
            mid = first + last / 2
            found = [ex(mid)]
            if number > found:
                first == mid
            if number < found:
                last == mid
            if number == found:
                print ("number found")
                print (str(found))

问题似乎是mid = first + last / 2等式......

2 个答案:

答案 0 :(得分:1)

嘿,我刚刚修改了你的代码,并在更改中添加了评论:) 但是你的代码将进入无限循环,因为你从未将完成设置为True

ex = [3, 4, 19, 42, 53, 23, 5, 8, 20] #list used
number = input("What number do you want to find?: ")
length = len(ex) - 1
first = 0
last = len(ex) #the square brackets created a list with only the length as one Element.
done = False
while done == False:
    for i in range(length):
        if ex[i] > ex[i+1]:
            sort = False
            ex[i], ex[i+1] = ex[i+1], ex[i] #flips the numbers in the list
        else:
            print (ex)
            mid = first + int(last / 2) #python creates a float as result of div
            found = ex[mid] # the see command above and you need to use square brackets to access list elements via index...
            if number > found:
                first == mid
            if number < found:
                last == mid
            if number == found:
                print ("number found")
                print (str(found))

答案 1 :(得分:1)

ex = [3, 4, 19, 42, 53, 23, 5, 8, 20] #list used
number = int(input("What number do you want to find?: "))
length = len(ex) - 1
first = 0
last = len(ex)-1;
done = False
#Sort the list first
ex.sort();
#Binary Search
while first > last :
            mid = int((first + last) / 2)
            found = ex[mid]
            if number > found:
                first = mid
            if number < found:
                last = mid
            if number == found:
                print ("number found")
                print (str(found))
                done=True;
                break;
if done == False :
    print("Number not found")