我创建的搜索算法依赖于排序算法(很多人在前面的问题中已经看到)。我相信排序算法不会更好(对于像我这样的初级程序员),但是我想知道您对我对搜索算法的描述有什么看法。
我将感谢您对我的代码的注释部分的洞察力(同样,对于搜索算法)。如果我能做任何其他的改变,请不要犹豫,让我知道。
def sorting_algorithm(list):
for index in range(1, len(list)):
current = list[index]
while index > 0 and list[index - 1] > current:
list[index] = list[index - 1]
index = index - 1
list[index] = current
return list
print("the sorted list is", (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57])))
#SEARCHING ALGORITHM CODE:
def searching_algorithm(list, num):
fir = 0 #the first number of the list.
las = len(list)-1 #the last number of the list.
i = -1 #the index is at the last number of the list.
while (fir <= las) and (i == -1): #the first number is less than or equals to the last number and the
#index is at -1 (so the last number).
mid = (fir + las) // 2 #the middle number is equal to the first num divided by the last number
#but without the remainder part.
if list[mid] == num: #if the middle number of the list equals the number
i = mid #then the index is moved to the middle number of the list.
else: #if that isn't true then we move on to the following condition.
if num<list[mid]: #if the number is less than the middle number of the list
las = mid -1 #then the index moves one to the right.
else: #if that isn't true either, then move on to the following condition.
fir = mid +1 #then the program will conclude that the number is the greater than
#the middle number.
return i
print("your number is at index",searching_algorithm([1, 7, 14, 23, 45, 57, 98, 102], 23))发布于 2020-12-02 05:26:55
fir + (las - fir) / 2确实更好。i == -1的测试看起来很难闻。大多数情况下,i仍然是-1,并且只有在找到目标号时才能得到有意义的值。当条件列表中 == num满足时,就需要立即对循环进行break,甚至return i。-1是不正确的。您的功能所做的所有工作都被突然放弃了。不要气馁,你在好公司里。标准C库中的bsearch也会造成同样的错误。返回一个插入点是非常有用的:目标号码应该在哪里。看看bisect.bisect_left()是如何做到这一点的( C++ std::lower_bound也是如此)。发布于 2020-12-02 17:44:01
首先,一个新程序员的伟大尝试。我看到您已经为搜索算法实现了二进制搜索,为排序算法实现了插入排序。
对于您的注释问题,您不希望逐字逐句地写每一行代码所做的事情。像fir = 0 # the first number of the list一样,您不需要写这个,因为这是常识,i = -1 # the index is at the last number of the list也是如此。您不应该做的另一个例子是:if num < list[mid]: # if the number is less than the middle number of the list- -这可能为您提供清晰的信息,但是对于某些人来说,这是不必要的。因此,您应该保留这些东西供您自己参考(无论您在哪里编写这段代码,不管它是空闲的,PyCharm等等),而不是在这样的平台上发布(相信我,您将受到批评)。
您也许应该在一堆代码的顶部添加一条注释,解释该代码将做什么。记住要简洁,不要写每一行代码都在做什么的段落。你的程序很小,所以很难找到不同的例子,但没关系,我们可以只使用我们所拥有的。
例如:
#write here what this 'chunk' or 'block' of code is for in ONE sentence here
while (fir <= las) and (i == -1):
mid = (fir + las) //
if list[mid] == num:
i = mid
else:
if num<list[mid]:
las = mid -1
else:
fir = mid +1是的,有时过度解释要比解释不足好,但有时你只需要把最基本和最原始的事实都说出来(尽量不要给出太多的细节!)
再次,我赞扬你的伟大尝试(对于初学者),并希望这个答案能够给你一些观点,你应该如何使用评论!
https://codereview.stackexchange.com/questions/252910
复制相似问题