简体   繁体   中英

How to sum items from largest value to smallest (python)

I am trying to write a program that will sum the items from a list, from largest to smallest, up to a certain value. (It´s an exercise on the "knapsack problem"). I have come up with this to find the largest valued item on the list and then add it to the variables pt and vt :

knapsack = []
l1 = [300.0, 400.0, 600.0, 1300.0, 2000.0]
l2 = [100.0, 400.0, 300.0, 700.0, 2000.0]
l3 = [0.3333333333333333, 1.0, 0.5, 0.5384615384615384, 1.0]
    
    while pt <= c:
        for i in range(len(l3):
            if i not in knapsack:
                if l3[i] > m:
                    m = l3[i]
                    v = l2[i]
                    p = l1[i]
                    knapsack.append(i)
                    
                if l3[i] == m and l1[i] < p:
                    m = l3[i]
                    v = l2[i]
                    p = l1[i]
                    knapsack.append(i)

            i += 1
        i = 0
        pt += p
        vt += v

However, I have not been able to make the for loop skip the previous largest value found, so it adds 400 to both pt and vt in every iteration. I tried solving that adding the i value to the knapsack list but it did not work.

OBS: the goal is to add to the knapsack the value with the largest value l1 to weight l2 ratio, for which I created a third list l3 . If the ratio is the same, the tie-breaking criteria is the item with the smallest weight, that is why the .sort() function wouldn´t work – each value has 2 correspontant values in the other lists.

Here is a solution:

# the input lists
l1 = [300.0, 400.0, 600.0, 1300.0, 2000.0]
l2 = [100.0, 400.0, 300.0, 700.0, 2000.0]

# the result list
l3 = [l2[i]/l1[i] for i in range(len(l1)) ]


# the sorted list (highest to lowest)
reversed_sorted = sorted(l3, reverse=True)


# some value to be used as a limit
some_value = 3


the_total=0 # value to keep adding
for i in reversed_sorted:
    if the_total + i >  some_value:
        # if go above value then exit
        break
    else:
        the_total = the_total + i
        # otherwise add next item

# print result
print(the_total)

note that the final loop cna be condensed into a list comprehension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM