【问题标题】:binary search to find the index of an item which is inside a list of dictionaries二进制搜索以查找字典列表中的项目的索引
【发布时间】:2020-12-10 22:53:57
【问题描述】:

我有一个包含字典的列表:

array =  [
    {"name": "Earth", "Density": 5.427},
    {"name": "Mars", "Density": 5.513},
    {"name": "Venus", "Density": 5.204},
]
element = input("What planet are you looking for? ")

该函数应返回项目的索引(在本例中为行星),如果不存在则返回 -1。

F.e | For input= Earth, expected output would be: 0
For input = Venus, expected output: 2

binary search 是这项任务的必备品。

My code gives TypeError: '<' not supported between instances of 'str' and 'dict

我的代码:

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

【问题讨论】:

  • binary search 仅在对数组进行排序时起作用。我认为您的数组未排序。
  • 按名称排序
  • 如果是这样,请尝试array[mid]["name"]。您正在比较strdict
  • 谢谢!效果很好

标签: python python-3.x list dictionary


【解决方案1】:

尝试用整数代替“名称”并对其进行相应排序,然后对其进行二进制搜索...

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2021-02-27
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多