most recent 30 from stackoverflow.com 2026-03-01T05:26:50Z https://stackoverflow.com/feeds/question/63744415 https://creativecommons.org/licenses/by-sa/4.0/rdf https://stackoverflow.com/q/63744415 2 Corel https://stackoverflow.com/users/4402306 2020-09-04T15:55:12Z 2020-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#63744522 1 Thierry Lathuille https://stackoverflow.com/users/550094 2020-09-04T16:01:12Z 2020-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 &lt;= 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#63744566 2 alani https://stackoverflow.com/users/13596037 2020-09-04T16:03:49Z 2020-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 &gt; 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#63744794 0 ponylama https://stackoverflow.com/users/10838062 2020-09-04T16:19:47Z 2020-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&lt;=n: max_sum_list.append(sorted_lst_second_element[i]) else: break print(sorted_lst_second_element) print(max_sum_list) </code></pre>