简体   繁体   中英

Binary Search Tree isn't assigning value

So I am trying to make a decision tree to choose the best cow. I have tried various ways of getting the values but I cant see to get them to stick to the decision. Any help would be really appreciated.

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)

So in this case I would want it to return Milkshake Lola and Florence because that adds up to exactly 16.

When trying to run your code it seemed to me the only problem was the indentation in certain areas that would throw errors. Once I fixed those the output I received was what you were looking for. Specifically the indentation in lines:

return result

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

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

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