【问题标题】:How Do I Perform a Binary Search Within a Nested List?如何在嵌套列表中执行二进制搜索?
【发布时间】:2021-07-23 01:56:19
【问题描述】:

问题是:

在课堂上,体育老师记录了学生的身高。

对于运动会,他必须根据身高升序创建学生列表。然后他需要找到 选择身高大于或等于 58 英寸的人参加特定运动。

注意:使用选择排序对学生进行排序,使用二分搜索搜索该列表中的学生。

编写 PAC、算法和 python 代码来实现它们。

输入:

Enter the number of students N
For each N student 
Enter the regno.
Enter the height.

输出:

List of students’ Reg numbers (sorted in order of height)
Register no of the students having height greater than or equal to 58 inches / NOT FOUND

到目前为止我做了什么:

D=[]
n = int(input("enter number of students:"))

for i in range(0, n):
    regno=input('enter registration number: ')
    height=int(input('enter hieght of student: '))
    D.append(['regno' , regno, 'height' , height])

D.sort(key=lambda x: x[3])

现在呢?

【问题讨论】:

  • 几个问题.. 你知道什么是选择排序吗?二进制搜索?这感觉就像多个问题合二为一。
  • 我应该将它们保存在 pdf 中。我完全知道我使用的排序命令不是选择排序,但我不能使用这个嵌套列表。请帮助我必须在 2 小时内(今天)提交此文件
  • 这是你的作业吗?
  • 不,它会被评分,称之为作业。请张贴代码

标签: python-3.x binary-search


【解决方案1】:

在我看来,这个问题并不完全正确,因为它要求执行二进制排序以查找高于或等于 58 的高度。二进制排序仅在身高为 58 英寸的人在场时才有效,因为在这种情况下,我们可以精确地获得包含高度 58 的元素的索引。但是如果不存在高度 58 即如果存在高度为 59,60,61... 的人,则二进制搜索将不起作用。 这是我基于您的方法构建的解决方案:

D=[]
n = int(input("enter number of students:"))

# entering the required data to the lists
for i in range(0, n):
    regno=input('enter registration number: ')
    height=int(input('enter height of student: '))
    D.append(['Regno:',regno,'Height:', height])

# performing selection sort (in ascending order)

for step in range(len(D)):
        min_id = step
        for i in range(step + 1, len(D)):
         
            if D[i][3] < D[min_id][3]:
                min_id = i
        (D[step], D[min_id]) = (D[min_id], D[step])

#comparing the heights of the students to find the index of the student whose height is nearest to 58 .

for i in range(len(D)):
    if D[i][3]<58:
        continue
    elif D[i][3] >=58:
        index=i
        break
# once we get the index of the student whose height is the nearest to 58 , we use list slicing to display the records starting from that index.
print("The list of students whose height greater than or equal to  58 inches:")
print(D[index:])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多