简体   繁体   中英

TypeError: unsupported operand type(s) for +: 'int' and 'list'

I keep getting this error for my code for a Binary Search function

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

the problem seems to be the mid = first + last / 2 equation...

Hey i just fixed your Code and added comments to the changes :) But your Code will get into a endless loop because you never set done to 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))
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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM