I have a list containing dictionaries:
array = [
{"name": "Earth", "Density": 5.427},
{"name": "Mars", "Density": 5.513},
{"name": "Venus", "Density": 5.204},
]
element = input("What planet are you looking for? ")
The function should return the index of an item(planet in this case) or -1 if it doesn't exist.
F.e | For input= Earth, expected output would be: 0
For input = Venus, expected output: 2
The binary search
is a must-have in this task.
My code gives TypeError: '<' not supported between instances of 'str' and 'dict
My code:
array = [
{"name": "Earth", "Density": 5.427},
{"name": "Mars", "Density": 5.513},
{"name": "Venus", "Density": 5.204},
]
element = input("What planet are you looking for? ")
def DeletePlanet(array, element):
mid = 0
start = 0
end = len(array)
step = 0
while start <= end:
step = step + 1
mid = (start + end) // 2
if element == array[mid]:
return mid
if element < array[mid]:
end = mid - 1
else:
start = mid + 1
return -1
print(DeletePlanet(array, element))
Instead of "Name" try to replace it with Integer and sort it accordingly and then do your binary search on it...
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.