【问题标题】:Binary search of sorted list that find the closest value in list to targeted value provided by the user Python 3排序列表的二进制搜索,在列表中找到与用户提供的目标值最接近的值 Python 3
【发布时间】:2020-03-25 10:20:04
【问题描述】:

有人可以帮助我如何访问所有浮点值并进行二进制搜索,以便如果匹配,它将输出列表中第二个的标题。例如,如果匹配 0.369,则查看下面的输出,它将输出 selfish。 谢谢。

到目前为止,列表的输出是 [['0.369', 'selfish', 'Future'] ['0.412', 'family', 'Future']] 列表是根据十进制值排序的从小到大全部存储在 storage = [ ]

【问题讨论】:

  • 你需要实现二分查找,还是其他可以使用的数据结构?没有二分搜索也有其他方法。
  • 不幸的是,我不得不使用二进制搜索方法。
  • 如果没有其他方法可以访问排序列表中的所有十进制数字?我可以尝试找出二进制部分。

标签: python-3.x list sorting search binary-search


【解决方案1】:

如果我理解正确,这就是您要找的东西:

def binary_search(storage, target):
    first = 0
    last = len(storage) - 1
    while first <= last:
        mid = (first + last) // 2
        value = float(storage[mid][0])
        if target == value:
            return storage[mid][1]
        elif value < target:
            first = mid + 1
        else:
            last = mid - 1
    return -1


storage = [["0.369", "selfish", "Future"], ["0.412", "family", "Future"]]

target = float(input("Please enter the desired float "))

result = binary_search(storage, target)
print(result)

请确保添加数据验证。例如,如果用户输入无效值“abc”会发生什么?

【讨论】:

  • omg 非常感谢您,您实际上是救生员,谢谢您,先生,我将添加一个全面的声明,以避免无效输入
猜你喜欢
  • 2019-10-13
  • 1970-01-01
  • 2014-12-27
  • 2012-11-14
  • 2015-07-26
  • 2022-11-28
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多