cards= [20,19,18,17,16,15,13, 11, 10, 7, 4, 3, 1, 0],
query=1
def checker(cards,query,mid,lo,hi):
mid_number = cards[mid]
print('mid',mid,', mid_number: ',mid_number,' lo ',lo,' hi ',hi)
if mid_number == query:
if mid-1>=0 and cards[mid-1] == query:
return 'left'
else:
return 'found'
elif mid_number<query:
return 'left'
else:
return 'right'
def locate_card(cards, query):
lo, hi = 0, len(cards) - 1
while (lo hi) // 2 != query:
mid = (lo hi) // 2
result = checker(cards,query,mid,lo,hi)
if result == 'found':
return mid
elif result == 'left':
hi = mid - 1
elif result == 'right':
lo = mid 1
print(locate_card(cards, query))
output
elif mid_number<query:
TypeError: '<' not supported between instances of 'list' and 'int'
CodePudding user response:
In you code you write: (pay attention to ,
in the end of line)
cards= [20,19,18,17,16,15,13, 11, 10, 7, 4, 3, 1, 0],
this code convert cards to the tuple
and when you write cards[0]
this return :
>>> cards[0]
[20,19,18,17,16,15,13, 11, 10, 7, 4, 3, 1, 0]
to mid_number
and when you check mid_number
with int
you check list
with int
and got an error.
Then you need to change this line like below:
>>> cards= [20,19,18,17,16,15,13, 11, 10, 7, 4, 3, 1, 0]
>>> cards[0]
20
CodePudding user response:
Try comparing the values from a for loop.
for i in cards:
if i == mid:
if i < query:
return 'left'
{...}