简体   繁体   中英

Infinite Loop i don't know why ( DichotomySearch )

so i'm working on a program that search a term by dichotomy. It makes an infinite loop and i don't know why but i know where ( in the elif/else ). So here is my code :

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)

I know there is plenty ways of doing it more easily but i need to keep the List untouched. Thanks you already guys!

You have a line in your code:

liste[DebutListe:FinListe]

that doesn't do anything, as the result is not stored. You'll need to reassign this if you want it to work:

liste = liste[DebutListe:FinListe]

Here's an implementation of binary search that more strictly adheres to Python's style guide:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM