【问题标题】:How to search a specific data in sorted list or given data?如何在排序列表或给定数据中搜索特定数据?
【发布时间】:2020-01-22 18:17:10
【问题描述】:
def BinarySearch(data_of_xyz, search_key):
    low_indx = 0
    hig_indx = len(data_of_xyz) -1
    found = False
    while low_indx<=hig_indx and not found:
        mid_indx = (low_indx + hig_indx) // 2
        if search_key == data_of_xyz[mid_indx]:
            found = True
        elif search_key > data_of_xyz[mid_indx]:
            low_indx = mid_indx + 1
        else:
            hig_indx = mid_indx - 1
    if found == True:
        print("Your search key is at position: ")
    else:
        print("Your key is not found: ")

data_of_xyz = [13, 24, 32, 35, 78]
data_of_xyz.sort()
print(data_of_xyz)
search_key = int(input("Enter the required key: "))
BinarySearch(data_of_xyz,search_key)

输出

Enter the required key: 35
Your search key is at position: 

如果您看到它没有显示列表中的第 35 位!

【问题讨论】:

  • 拥有found = data_of_xyz.index(search_key) if search_key in data_of_xyz else None不是更容易吗?或者您只是想知道您对搜索功能的实现是否正确?
  • 变量和函数名称应遵循lower_case_with_underscores 样式。你觉得if found == True: 是如何工作的?

标签: python sortedlist


【解决方案1】:

它没有打印值,因为您告诉它只打印标题文本,而不是值。

if found:
    print("Your search key is at position: ", mid_indx)

解决问题:

[13, 24, 32, 35, 78]
Enter the required key: 35
Your search key is at position:  3

【讨论】:

  • 是的!你是对的,它确实像你提到的那样工作,谢谢 Prune!
猜你喜欢
  • 2021-12-15
  • 2013-04-28
  • 1970-01-01
  • 2021-08-04
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
相关资源
最近更新 更多