Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list in almost equal parts and return bounds

I would like to split a list and return the bounds so in extend no single element should exist.

E.g

split(list(range(1,101)),2) 
# should return 
[[1,50],[51,100]]

split(list(range(1,101)),3)
# should return
[[1,33],[34,66],[67,100]]

split(list(range(1,6)),3)
# should return
[[1,2],[3,5]] # Ideally last element should merge with last if last one has no pair.

So far I tried

def split(l, n):
    x = list(range(1, l+1))
    return [x[i:i+n] for i in range(0, len(x), int(len(x)/n))]

print(split(20, 2))

which returns [[1, 2], [11, 12]] instead of [[1, 10], [11, 20]]

like image 803
Panos Kal. Avatar asked Nov 25 '25 10:11

Panos Kal.


1 Answers

This should help, it is not useing the full range of list, but just the "borders" you are interested in, some creative zip()ping and fixes whats wrong after creating the ranges:

def split(l, n):
    stride =(l//n)
    r = list(range(1, l+stride, stride))  # overbuild needed range

    # adjust zipped value by 1 if needed
    k = [ [a , b-1 ] for a,b in zip(r,r[1:]) ]

    # fix special cases 
    for _ in range(n+1): # guesstimate of fixes needed

        if k[-1][0] == k[-1][1]: # last pair identical 
            k.pop()    # remove it and fix new last index to be l  instead
            k[-1][1] = l        
        elif k[-1][1] != l:
            k[-1][1] = l

    return k

print(split(100, 2))
print(split(100, 4))
print(split(103, 3))
print(split(6, 3))

Output:

[[1, 50], [51, 100]]                          # split(100, 2)
[[1, 25], [26, 50], [51, 75], [76, 100]]      # split(100, 4)
[[1, 34], [35, 68], [69, 103]]                # split(103, 3)
[[1, 2], [3, 4], [5, 6]]                      # split(6, 3)

I gave it a cursory testing with your examples, check the logic if it fits all your special cases.

Especially the # guesstimate of fixes needed might be too many... I have a hunch that at most 2 should be enough

like image 199
Patrick Artner Avatar answered Nov 27 '25 01:11

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!