为了账号安全,请及时绑定邮箱和手机立即绑定

去元组替代

去元组替代

Go
哔哔one 2022-07-11 10:35:02
我正在学习麻省理工学院计算思维和数据科学导论课程第 2课讲座 PDF,我正在尝试将以下树搜索算法 python 代码翻译成 Golang。主要问题是python代码使用了一个元组。def maxVal(toConsider, avail):    """Assumes toConsider a list of items, avail a weight       Returns a tuple of the total value of a solution to the         0/1 knapsack problem and the items of that solution"""    if toConsider == [] or avail == 0:        result = (0, ())    elif toConsider[0].getCost() > avail:        #Explore right branch only        result = maxVal(toConsider[1:], avail)    else:        nextItem = toConsider[0]        #Explore left branch        withVal, withToTake = maxVal(toConsider[1:],                                     avail - nextItem.getCost())        withVal += nextItem.getValue()        #Explore right branch        withoutVal, withoutToTake = maxVal(toConsider[1:], avail)        #Choose better branch        if withVal > withoutVal:            result = (withVal, withToTake + (nextItem,))        else:            result = (withoutVal, withoutToTake)        return resultdef testMaxVal(foods, maxUnits, printItems = True):    print('Use search tree to allocate', maxUnits,          'calories')    val, taken = maxVal(foods, maxUnits)    print('Total value of items taken =', val)    if printItems:        for item in taken:            print('   ', item)我知道 Go 没有元组,我四处寻找解决方法。我尝试了这个解决方案但没有运气:type Food struct {    name     string    value    int    calories int}type Pair struct{ //found this work around on another stack overflow question but I think I incorrectly implemented it     a,b interface{}}
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

Go 没有元组,但它可以返回多个值:


func maxval(toConsider []Food, avail int) (int,[]Food) {

   if len(toConsider)==0 || avail == 0) { // len(toConsider)==0 will work even if toConsider is nil

      return 0,nil

   }

 ...

}


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号