Двоичное дерево поиска не присваивает значение - PullRequest
0 голосов
/ 29 февраля 2020

Поэтому я пытаюсь составить дерево решений, чтобы выбрать лучшую корову. Я пробовал разные способы получения значений, но не вижу, чтобы они придерживались решения. Любая помощь могла бы быть полезна.

def brute(data,limit): #data is the list and limit is the most one trip can have
    if data == [] or limit == 0:#check if the list is empty or if the limit is reach
        result = ()#the result of the solutions
    elif data[0][1] > limit: # if the limit has been exceeded move on
        return brute(data[1:],limit)
    else:
        current_cow = data[0] #get the first item in the list
        """Here I want to begin the process of exploring the decesion tree 
           I want with_cow to be the first item and with_value to be the weight 
           of that cow"""
        with_cow,with_value = brute(data[1:],limit - data[0][1]),current_cow[1] 
        if with_cow != (): #I want to get the value if its not empty and add it up
            with_value += with_cow[1]
        else:
            with_value += 0 
        with_cow += current_cow

        "Here I want to do the same as with_cow but I want it to be the right branch"
         without_cow,without_value = brute(data[1:],limit),current_cow[1]
        if without_cow != ():
            without_value += without_cow[1]
        else:
            without_value += 0 
        without_cow += current_cow

        if with_value > without_value: #set result to be the better branch 
            result = with_cow
        else:
            result = without_cow

return result 


 cows = [('Moo Moo', 9.0), ('Milkshake', 6.0), ('Lola', 8.0), 
('Florence', 2.0)]

brute(cows,16)

Так что в этом случае я бы хотел, чтобы он вернул Молочный коктейль Лоле и Флоренции, потому что это в сумме равно 16.

1 Ответ

0 голосов
/ 29 февраля 2020

При попытке запустить ваш код мне показалось, что единственная проблема заключалась в отступе в некоторых областях, которые могут приводить к ошибкам. Как только я исправил эти данные, вы получили именно то, что искали. Конкретно отступ в строках:

return result

without_cow,without_value = brute(data[1:],limit),current_cow[1]

cows = [('Moo Moo', 9.0), ('Milkshake', 6.0), ('Lola', 8.0), 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...