簡體   English   中英

TypeError:+不支持的操作數類型:“ int”和“ list”

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

我的二進制搜索功能代碼不斷收到此錯誤

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

問題似乎是中=第一個+最后一個/ 2等式...

嘿,我剛剛修復了您的代碼並為更改添加了注釋:)但是您的代碼將陷入無休止的循環,因為您從未將done設置為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")

暫無
暫無

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

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