Uma função recursiva para verificar se o elemento está na lista SORTED

Nov 27 2020

Não gosto muito de funções recursivas e estou pedindo para mudar minha função em funções recursivas e mais otimizadas. Sei que nesta tarefa devo aproveitar o fato de que essa lista está ordenada, mas não sei como, talvez algum tipo de bolha? Esse é o meu código, bem simples, mas nem recursivo, e não leva em conta se a lista está ordenada ou não.

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")

Respostas

2 Denis Nov 27 2020 at 21:52

o que você pode fazer é usar devide e conquistar, o que significa:

O algo é assim:

Você tem uma lista classificada de n elementos no total. Checkin array se o elemento em n / 2 é o que você está procurando Se não for, sendo uma lista ordenada, você sabe que todos os elementos de n / 2 -> n são maiores, e todos os elementos de 0 -> n / 2 são menores. Verifique se o número em n / 2 é menor ou maior do que o que você está procurando. Se for menor, você executa a mesma função novamente, mas agora, você fornece apenas um subconjunto da lista, ou seja, se for menor, você fornece 0 -> n / 2, se for maior, você fornece n / 2 -> n . Claro que você precisará de algumas condições de parada, mas hey, este é o algo.

Essa é a teoria, aqui está o código.

Não é a melhor implementação disso, apenas do topo da minha mente.

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)