[英]Infinite Loop i don't know why ( DichotomySearch )
所以我正在研究一个通过二分法搜索术语的程序。 它造成无限循环,我不知道为什么,但是我知道在哪里(在elif / else中)。 所以这是我的代码:
def RechercheDichotomique(liste,x):# Algo pour recherche dichotomique
DebutListe=0
FinListe=len(liste)
while (FinListe-DebutListe)>1:# On ne cherche que si la liste a au moins un terme dedans
ElementCentral=int(len(liste[DebutListe:FinListe])/2)# On prend l'element central de la liste
liste[DebutListe:FinListe]
if liste[ElementCentral]==x:# Si l'element central est x correspondent on renvoie True
return (True)
elif liste[ElementCentral]<x:# Si l'element central est inferieur a x alors on prend la moitie superieure
DebutListe=ElementCentral
FinListe=len(liste)
else:# Sinon on prend la partie inferieure de la liste
DebutListe=0
FinListe=int((FinListe)/2)
if FinListe-DebutListe==1 and liste[ElementCentral]==x:# On verifie qu'il ne reste qu'un terme dans la liste et que le seul qui reste est bien x
return (True)
我知道有很多方法可以更轻松地完成此操作,但我需要保持列表不变。 谢谢你们已经!
您的代码中有一行:
liste[DebutListe:FinListe]
不会执行任何操作,因为不会存储结果。 如果您希望它能正常工作,则需要重新分配它:
liste = liste[DebutListe:FinListe]
这是二进制搜索的一种实现,更严格地遵循Python的样式指南:
def binary_search(collection, x):
while collection:
center = len(collection) / 2
if collection[center] == x:
return True
elif collection[center] < x:
collection = collection[center + 1:]
else:
collection = collection[:center]
else:
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.