Funkcja rekurencyjna do sprawdzania, czy element znajduje się na liście SORTOWANE

Nov 27 2020

Tak naprawdę nie interesuję się funkcją rekurencyjną i proszę o zmianę funkcji na rekurencyjną i bardziej optymalną. Wiem, że w tym zadaniu powinienem wykorzystać fakt, że ta lista jest posortowana, ale nie wiem jak, może jakieś bąbelkowe sortowanie? To jest mój kod, dość prosty, ale nawet nie rekurencyjny i nie bierze pod uwagę, czy lista jest posortowana, czy nie.

list1 = [1, 2, 3, 4, 5, 6]


def is_in_List(x):
    if x in list1:
        return True
    else:
        return False


x = 3

if is_in_List(x):
    print(f"{x} is in list")
else:
    print(f"{x} is not in list")

Odpowiedzi

2 Denis Nov 27 2020 at 21:52

co możesz zrobić, to użyj dziel i podbijaj, co oznacza:

Algo wygląda tak:

Masz posortowaną listę n wszystkich elementów. Tablica sprawdzania, jeśli element n / 2 jest tym, którego szukasz Jeśli nie, będąc posortowaną listą, wiesz, że wszystkie elementy z n / 2 -> n są większe, a wszystkie elementy z 0 -> n / 2 są mniejsze. Sprawdź, czy liczba pod adresem n / 2 jest mniejsza lub większa niż ta, której szukasz. Jeśli jest mniej, uruchamiasz tę samą funkcję ponownie, ale teraz dajesz jej tylko podzbiór listy, czyli jeśli jest mniejsza, dajesz 0 -> n / 2, jeśli jest większa, dajesz n / 2 -> n . Oczywiście będziesz potrzebować pewnych warunków zatrzymania, ale hej, to jest algo.

Taka jest teoria, oto kod.

Nie jest to najlepsza realizacja, tylko z góry mojej głowy.

my_list = [1,2,3,4,5,6,7,8,9];


def binary_search(a_list, search_term):

    #get the middle position of the array and convert it to int    
    middle_pos = int((len(a_list)-1)/2)
    
    #check if the array has only one element, and if so it it is not equal to what we're searching for, than nothing is in the aray
    
    if len(a_list) == 1 and search_term != a_list[middle_pos] :
        #means there are no more elements to search through
        return False
    
    #get the middle term of the list
    middle_term = a_list[middle_pos]
    
    #check if they are equal, if so, the number is in the array
    if search_term == middle_term:
        return True
    
    #if the middle is less than search, it means we need to search in the list from middle to top
    if middle_term < search_term : 
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[middle_pos:len(a_list)], search_term)
        
    else : 
        #on else, it means its less, we need to search from 0 to middle
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[0:middle_pos], search_term)
        
print(binary_search(my_list, 1)