TypeError:“ list”和“ int” Python实例之间不支持“>”

时间:2019-05-02 05:41:40

标签: python algorithm

在需要生成1000个随机元素的事物上工作,然后还生成一个称为“搜索值”的随机元素,然后将其传递给二进制搜索并打印是否找到“搜索值” ...但是错误

代码:

def binarySearch(item_list,item):
    first = 0
    last = len(item_list)-1
    found = False
    while( first<=last and not found):
        mid = (first + last)//2
        if item_list[mid] == item :
            found = True
        else:
            if item < item_list[mid]:
                last = mid - 1
            else:
                first = mid + 1
    return found

arr = [random.randrange(9999) for x in range(1000)]
searched_value = [random.randrange(0,1000)]
print(binarySearch(arr, searched_value))

错误:

line 19, in <module>
    print(binarySearch(arr, searched_value))

line 11, in binarySearch
    if item < item_list[mid]:

TypeError: '<' not supported between instances of 'list' and 'int'

2 个答案:

答案 0 :(得分:2)

这行代码在这里

ag109 9.917E-07
am241 3.577E-06
am243 8.752E-08
cs133 2.112E-05
eu151 2.935E-08
eu153 1.132E-06
gd155 3.786E-08
mo95 1.979E-05
nd143 1.641E-05
nd145 1.181E-05
np237 3.017E-06

应该是

searched_value = [random.randrange(0,1000)]

您正在创建列表而不是随机数

答案 1 :(得分:1)

searched_value = [random.randrange(0,1000)]

===>

searched_value = random.randrange(0,1000)

因为searched_value是列表,而item_listpmid]是int。