简体   繁体   中英

TypeError: '>' not supported between instances of 'list' and 'int' Python

Working on something where I need to generate 1000 random elements, then also generate a single random element called "searched value" then pass it through binary search and print weather the "searched value" was found or not... but getting an error

Code:

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

Errors:

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'

This line of code here

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

should be

searched_value = random.randrange(0, 1000)

As it is you are creating a list and not a random number

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

===>

searched_value = random.randrange(0,1000)

Because, searched_value was list but, item_listpmid] is int.

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