繁体   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