【问题标题】:how to apply binary search in python on sorted list of string elements?如何在python中对字符串元素的排序列表应用二进制搜索?
【发布时间】:2015-11-17 19:33:03
【问题描述】:

我有一个字符串元素(城市名称)的排序列表,我想对此进行二分搜索并通过给出首字母来过滤掉城市?

例如用户输入:http://127.0.0.1:8000/api/?city=New

所以在这种情况下,我需要找出从 New 开始的城市

样本输出:

[
"New Abbey|Ceredigion|United Kingdom",
"New Albany|Indiana|United States",
"New Albany|Kansas|United States",
"New Albany|Mississippi|United States",
"New Albany|Ohio|United States"
]

请指教。

【问题讨论】:

标签: python django binary-search


【解决方案1】:

以下方法应该有效。它使用 Python 自己的名为 bisect 的二进制搜索库来查找列表中的初始索引。对于搜索词 New,它返回 2 作为我的示例列表。 itertools.takewhile 然后可用于返回条目,直到您的搜索词失败:

import bisect, itertools

locations = [
    "Aaaa|aaaa|Test",
    "Bbbb|bbbb|Test",
    "New Abbey|Ceredigion|United Kingdom",
    "New Albany|Indiana|United States",
    "New Albany|Kansas|United States",
    "New Albany|Mississippi|United States",
    "New Albany|Ohio|United States",
    "Zzzz|zzzz|Test"
    ]

search = "New"
start_index = bisect.bisect_left(locations, search)
print list(itertools.takewhile(lambda x: x.startswith(search), itertools.islice(locations, start_index, None)))

给出以下输出:

['New Abbey|Ceredigion|United Kingdom', 'New Albany|Indiana|United States', 'New Albany|Kansas|United States', 'New Albany|Mississippi|United States', 'New Albany|Ohio|United States']

【讨论】:

  • 非常感谢马丁 :)
【解决方案2】:

您可以使用list comprehension 过滤您想要的项目:

[x for x in cities if x.startswith('New')]

【讨论】:

  • 我已经完成了,但是我的老板要我实现二进制搜索。
  • 那是无法理解的。请不要在 cmets 中转储代码。
  • 您问如何查找以新开头的城市 - 答案就是这样。现在你在问binary search - 这是一个非常不同的事情 - 我认为你的老板可能会感到困惑
  • 我已经给了他两种解决方案,一种使用列表推导式,另一种使用正则表达式,但他说对此进行二分搜索会减少搜索时间。目前是迭代搜索,如果我们实现二分搜索,那么搜索城市的时间将会减少。
  • 好吧……也许吧。您可能希望有一个非常详细的城市列表,以便充分利用您的时间。
【解决方案3】:

如果您想在 python 中实现二进制搜索,那么这可能会对您有所帮助。

def binarySearch(alist, item):
    first = 0
    last = len(alist)-1
    found = False

    while first<=last and not found:
         midpoint = (first + last)//2
         if alist[midpoint] == item:
             found = True
         else:
             if item < alist[midpoint]:
                 last = midpoint-1
             else:
                 first = midpoint+1

    return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))    
print(binarySearch(testlist, 13))

来源:http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2015-05-16
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多