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

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

问题描述

我在此代码块之后附加或实际上打印任何内容时遇到问题:

I have an issue appending or in fact printing anything after this block of code:

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 循环是否存在某些条件?

I am expecting it to append [3,6] to numA and print but it currently does nothing. Is there some condition for the while loop that I'm overlooking?

代码的重点是找到'reversedPriv'中的哪些元素与'array'中的每个元素相加,并将它们附加到列表'numA'中.例如,从 'reversedPriv' 列表中只有 6 和 3 总和为 9.所以 numA = [3,6] 目前 'array' 只有一个元素,但代码应该能够将它扩展为 n 个元素.

The point of the code is to find which elements in 'reversedPriv' sum up to each element in 'array' and append them to the list 'numA'. For example from the list of 'reversedPriv' only 6 and 3 sum up to 9. So numA = [3,6] Currently 'array' only has a single element but the code should be able to scale it up for n number of elements.

推荐答案

因此,总的来说,在 SO 上明确问题是什么是个好主意,但通常最好提供问题的上下文.

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.

您正在处理的是背包求解器的一个片段.正如我在下面的评论中所提到的,您最好只使用开箱即用的 or-tools 如下(取自 https://developers.google.com/optimization/bin/knapsack):

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()

控制台:

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

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

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