[英]Binary Search Tree isn't assigning value
所以我试图制作一个决策树来选择最好的奶牛。 我尝试了各种获取价值的方法,但我无法让他们坚持这个决定。 任何帮助将非常感激。
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)
所以在这种情况下,我希望它返回 Milkshake Lola 和 Florence,因为加起来正好是 16。
在尝试运行您的代码时,在我看来唯一的问题是某些区域的缩进会引发错误。 一旦我修复了这些,我收到的输出就是你想要的。 特别是行中的缩进:
return result
without_cow,without_value = brute(data[1:],limit),current_cow[1]
cows = [('Moo Moo', 9.0), ('Milkshake', 6.0), ('Lola', 8.0),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.