python - 去元组替代

标签 python go

我正在通过麻省理工学院计算思维与数据科学概论类(class)第2讲The lecture 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 result

def 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{}
}



func maxVal(toConsider []Food, avail int) Pair{ 
    /*
    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
    */

    var result Pair //the culprit

    if (toConsider == nil || avail == 0){ //Slices can only be compared to nil so I am not sure this is achieving what I want it to achieve (i.e. checking for an empty list)

        result = Pair{0, nil}
    } else if toConsider[0].calories > avail{
        //explore right branch only
        result = maxVal(toConsider[1:], avail)
    } else{
        nextItem := toConsider[0]
        //explore left branch
        withVal, withToTake := maxVal(toConsider[1:], avail - nextItem.calories)
        withVal = withVal + nextItem.value
        //explore right branch
        withoutVal, withoutToTake := maxVal(toConsider[1:], avail)
        //choose better branch
        if withVal > withoutVal{
            result = Pair{withVal, withToTake + (nextItem)}
        }
    }
    return result
}

func testMaxVal(foods []Food, maxUnits int, printItems bool) {
    printItems = true
    fmt.Printf("Use search tree to allocate %d calories", maxUnits)
    val, taken := maxVal(foods, maxUnits)
    fmt.Printf("\nTotal value of items taken = %d", val)
    if printItems{
        for i := range taken{
            fmt.Print("\n ", i)
        }
    }
}

最佳答案

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
   }
 ...
}

关于python - 去元组替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325054/

相关文章:

Python:将整数写入二进制文件

json - Golang - 零值字节数组

go - 并发示例的值不正确

arrays - 创建一个没有 make 的 Go slice

go - 从 Golang 结构生成序列化器

python - 无法从 python 3.5.2 升级到 3.6

python - 如何在系统关闭时运行 Python 脚本 (Windows 7)

python - 如何删除回归中的虚拟变量之一

找不到 Python 模块错误 "No module named ' ortools'“

nginx - Gorilla WebSocket 一分钟后断开连接