most recent 30 from stackoverflow.com2026-03-01T05:26:50Zhttps://stackoverflow.com/feeds/question/63744415https://creativecommons.org/licenses/by-sa/4.0/rdfhttps://stackoverflow.com/q/637444152Corelhttps://stackoverflow.com/users/44023062020-09-04T15:55:12Z2020-09-04T16:19:47Z
<p>I have a list of tuples (the actual list can be very big), the first element in the tuple indicates the index, and the second indicates the value. I also have a number <code>n</code>:</p>
<pre class="lang-py prettyprint-override"><code>lst = [(0,1), (1,2), (2,4), (3,5), (4,1), (5,2)]
n = 6
</code></pre>
<p>I want to find the largest combination that will give me the sum of <strong>values</strong> which is less than or equal to <code>n</code>. So in this example the answer should be a list like the following:</p>
<pre class="lang-py prettyprint-override"><code>[(0,1), (1,2), (4,1), (5,2)]
</code></pre>
<p>because <code>1+2+1+2 = 6</code> is the largest combination of values in <code>lst</code> that yields a sum which is less or equal to <code>n</code>.</p>
<p>I need to find something that works on lists with, say, 200-300 elements at least.</p>
https://stackoverflow.com/questions/63744415/-/63744522#637445221Thierry Lathuillehttps://stackoverflow.com/users/5500942020-09-04T16:01:12Z2020-09-04T16:01:12Z<p>Start by sorting the tuples by value, then take as many as you can while staying under the limit:</p>
<pre><code>from operator import itemgetter
lst = [(0,1), (1,2), (2,4), (3,5), (4,1), (5,2)]
n = 6
sorted_list = sorted(lst, key=itemgetter(1))
out = []
total = 0
for index, value in sorted_list:
total += value
if total <= n:
out.append((index, value))
else:
break
print(out)
# [(0, 1), (4, 1), (1, 2), (5, 2)]
</code></pre>
https://stackoverflow.com/questions/63744415/-/63744566#637445662alanihttps://stackoverflow.com/users/135960372020-09-04T16:03:49Z2020-09-04T16:03:49Z<p>Using a copy of the list sorted in order of increasing value, accumulate tuples until the total would exceed the target, and then sort back into index order.</p>
<pre><code>lst = [(0,1), (1,2), (2,4), (3,5), (4,1), (5,2)]
n = 6
total = 0
answer = []
for tup in sorted(lst, key=lambda t:t[1]):
val = tup[1]
if total + val > n:
break
answer.append(tup)
total += val
answer.sort(key=lambda t:t[0])
print(answer)
</code></pre>
<p>Gives:</p>
<pre><code>[(0, 1), (1, 2), (4, 1), (5, 2)]
</code></pre>
https://stackoverflow.com/questions/63744415/-/63744794#637447940ponylamahttps://stackoverflow.com/users/108380622020-09-04T16:19:47Z2020-09-04T16:19:47Z<pre><code>lst = [(0,1), (1,2), (2,4), (3,5), (4,1), (5,2)]
n = 5
sorted_lst_second_element = sorted(lst, key=lambda x: x[1])
sum = 0
max_sum_list = []
for i in range (len(lst) - 1):
sum = sum + sorted_lst_second_element[i][1]
if sum<=n:
max_sum_list.append(sorted_lst_second_element[i])
else:
break
print(sorted_lst_second_element)
print(max_sum_list)
</code></pre>