Divide a list into two, making sum of sublist equal

2273 views python

Assume there is a list L=list(range(N)), and number n1 and n2 where n1+n2=sum(L). I want to def an function to divide L into L1 and L2 so that sum(L1)=n1 and sum(L2)=n2.

How to build this function in an effective way?


Given: N=7,n1=7,n2=14

We got: L=list(range(7))

We need func(L) returns [3,4] and [0,1,2,5,6]

answered question

Cn you show a toy example of the list and expacted output?

why it dose not returns [1,6] and [0,2,3,4,5] how it distributed?

@Ahmed Yousif Returning only one case that meet the requirement is enough.

It this homework?

1 Answer


if n1 + n2 = sum(L), then sum(L) - n2. Just build L2 first, and build L1 from what's left.

def split_list(L, n1, n2):
    L1, L2 = [], []  # new lists
    x = max(n1, n2)
    for n in reversed(L):
        if n <= x:
            n -= x
    return L1, L2

posted this

Have an answer?


Please login first before posting an answer.