-2

I have two lists:

list1 = [1,2,6]
list2 = []

And i have a number: N

How can I append the numbers of list1 to list2 so that the sum of the list2 is equal to N.

Exemple:

n = 10
list2 = [2,2,6]

I could not find a way to add the 2 until the sum equal to 10

taynan
  • 67
  • 1
  • 7

1 Answers1

0

This might work:

list1 = [1,2,6]
list2 = []
n = 10

list1 = sorted(list1, reverse=True) # sort list descending order

for i in list1:                     # for each item in list1
    list2.append(i)                 # add the item to list2
    while not sum(list2) >  n:      # while sum of list2 is less than n 
        list2.append(i)             # keep adding the same element
    if sum(list2) > n:              # if sum of list2 is more than n
        list2.pop()                 # remove the last element added

list2.sort() # sort list ascending order
print(list2) # [2, 2, 6]

Works for the given list1.

Might need to test on different length and numbers of list1.

  • Wow, that's awsome man, it's working. I had tried to do something similar, but instead "while not sum(list2) > n:", i tried "while sum(list2) <=n:", but for some reason it was not working :( Really thanks man – taynan Oct 10 '17 at 03:29
  • yeah you could probably do the same with "while sum(list2) <=n:" and change a few other things. glad to help. if you feel this answered your question, please consider upvoting or accepting it, thanks. – chickity china chinese chicken Oct 10 '17 at 03:33
  • reverse the list really was a great idea O.O – taynan Oct 10 '17 at 03:37