Skip to content Skip to sidebar Skip to footer

How To Alter This Code To Allow Appending To The List?

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 reversedP

Solution 1:

Instead of j it should be var != i:

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

Or without the while,

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

Or,

reversedPriv = [52,27,13,6,3,2]
array= [9]
var = 0
numA = []
numA = [sorted([x,y]) for x,y in zip(reversedPriv[:-1],reversedPriv[1:]) if x+y == array[0]][0]
print(numA)

Output:

[3, 6]

Solution 2:

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 = 0print('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:

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

Solution 3:

I am not sure what are you trying to do, but it'seems you want 6 + 3 = 9, append 6,3 to numA

for it1 in reversedPriv:for it2 in reversedPriv:sumit=it1+it2# sum 1st iteraction with 2nd iteractionifsumit==array[0]:#extract array value from listif it1 not in numA and it2 not in numA:numA.append(it1)numA.append(it2)print(numA)#[6, 3]

Post a Comment for "How To Alter This Code To Allow Appending To The List?"