Python: Binary Search - "Find the first occurrence"



这个有点麻烦。我在下面包含了我所拥有的内容。当我提交它时,由于某种原因,它一直说"程序超时"。我不确定下一步该怎么做。它在一定程度上有效,即某些测试有效,而不是最后一个测试不起作用。你有什么建议?

我已经附上了问题的屏幕截图,以及到目前为止我所拥有的内容。

这是类中的注释(伪代码(,我只需要修改它即可将其修改为在ordered_list中打印目标的第一次出现。如果列表中不存在目标,则必须返回 None。

提前谢谢你!!

问题: 你要编写一个 Python 函数的代码

优先搜索(有序列表,目标(

给定一个非空的有序项目列表和一个目标项目(所有类型相同(,如果目标在列表中,则返回列表中目标第一次出现的索引,否则返回 None 的索引。

例如,首先调用 binsearch ([1, 3, 3, 7, 9], 3( 应返回 1,因为前 3 位于索引 1 处。类似地,首先的呼叫二进制搜索([1, 3, 3, 7, 9], 9(应返回 4,而呼叫二进制搜索优先([1, 3, 3, 7, 9], 5( 应返回 None。

除了物品是可订购的之外,您不得对物品的类型做出任何假设。例如,项目可以是字符串,并且首先调用二进制搜索(["Alice","Bob","Chloe","Chloe","Dave"],"Chloe"(应返回2。

您的计划将被评估效率和风格。对于完全信用,它可能只对相等性进行一次测试(它可能只有一个"=="比较,此外,它可能不在任何循环中(。也就是说,唯一的相等性测试发生在执行结束时,就在返回之前。

限制:此问题不允许递归。 允许使用除

此外,你不是

, − ,/
  • /, × , <,

和(一次(==

当然,所有与搜索相关的内置和库函数也是不允许的:你必须自己进行编码。

def binsearch_first(ordered_list, target):
left = 0
right = len(ordered_list) - 1
count = 0
while left <= right:
mid = (left + right) // 2
count = count + 1
if ordered_list[mid] == target:
while mid > 0 and ordered_list[mid - 1] == target:
mid = mid - 1
return mid
elif target < ordered_list[mid]:
right = mid - 1
else:
left = mid + 1
return None

查找第一个匹配项

唯一使用字符串和整数的运算符是 <。 我们必须利用它是一个有序列表的事实 - 按递增顺序排列。

def binsearch(orderedlist,target):
candidate = 0
for i in range(len(orderedlist)):
if orderedlist[i] < target:
candidate = candidate
else:
if i+1 < len(orderedlist):
if orderedlist[i] < orderedlist[i+1]:
#it is an ordered list so if i+1 is not bigger than i, it must be equal
candidate = candidate
else:
candidate = i
break # can you use break?
if orderedlist[candidate] == target:
return candidate
else:
return None

我不是CS学生,因此无法评论该计划的有效性,但是您可以通过使用简单的for循环来实现目标

def binsearch_first(ordered_list, target):
i=0
for ele in ordered_list:
if ele == target:
return i 
break
else:
i+=1
return None 

其结果是:

>>> binsearch_first([1, 3, 3, 7, 9], 3)
1
>>> binsearch_first(["Alice", "Bob", "Chloe", "Chloe", "Dave"], "Chloe")
2

问候

相关内容

最新更新