如何更改此代码以允许附加到列表? [英] How to alter this code to allow appending to the list?

查看:90
本文介绍了如何更改此代码以允许附加到列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码块之后,我实际上无法添加或打印任何内容:

reversedPriv = [52,27,13,6,3,2]
array= [9]
var = 0
numA = []
for i in array:
    for j in reversedPriv:
        while var!= j:
            if j < i:
                var = var + j
                numA.append(j)
                numA.sort()
print(numA)

我希望它可以将[3,6]附加到numA并打印,但是目前不执行任何操作.我忽略的while循环是否存在某些条件?

代码的重点是找到'reversedPriv'中的哪些元素与'array'中的每个元素相加,并将它们附加到列表'numA'中.例如,从"reversedPriv"列表中,只有6和3的总和为9.因此numA = [3,6]当前数组"只有一个元素,但是代码应该能够将其放大为n个元素.

解决方案

因此,通常,SO最好弄清楚问题是什么,但通常最好提供问题的上下文. /p>

您正在研究的是背包解算器的一部分.如我在下面的评论中所述,您最好按照以下说明使用即装即用的工具(取自 解决方案

So in general, it's a good idea on SO to be clear about just what the question is, but it's often better to provide the context of your question.

What you are working on is a fragment of a knapsack solver. As mentioned in my comments below, you may do better to just use or-tools out of the box as follows (taken from https://developers.google.com/optimization/bin/knapsack):

from ortools.algorithms.pywrapknapsack_solver import KnapsackSolver

def knapsack():
    solver = KnapsackSolver(
       KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,
      'KnapsackExample'
    )
    weights = [[52,27,13,6,3,2]]
    capacities = [9]

    solver.Init(weights[0], weights, capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    print('Total value =', computed_value)
    for i in range(len(weights[0])):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]

    print('Total weight:', total_weight)
    print('Packed items:', packed_items)
    print('Packed_weights:', packed_weights)

knapsack()

Console:

Total value = 9
Total weight: 9
Packed items: [3, 4]
Packed_weights: [6, 3]

这篇关于如何更改此代码以允许附加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆