【问题标题】:TypeError: unsupported operand type(s) for +: 'int' and 'list'类型错误:+ 不支持的操作数类型:“int”和“list”
【发布时间】:2017-03-03 10:15:48
【问题描述】:

我的二进制搜索函数代码不断收到此错误

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 等式...

【问题讨论】:

  • 您已将last 定义为[len(ex)],所以last 确实是一个列表。
  • 您在 else 语句中遇到了与 found 类似的问题。
  • 这不是您要寻找的答案,但请记住,布尔值不需要使用== 检查,而是可以使用while not done 表示法来简化您的代码。

标签: python list int


【解决方案1】:

嘿,我刚刚修复了您的代码并在更改中添加了 cmets :) 但是您的代码将进入无限循环,因为您从未将 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))

【讨论】:

    【解决方案2】:
    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2013-10-04
      • 2021-06-16
      相关资源
      最近更新 更多