Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretching a list in Python

An example: I have a list [1,2,3,4,5,6,7,8] and I need to "stretch" it to lenght 20, with existing values distributed as evenly as possible,"missing" values replaced with None and the resulting list has to start with 1 and end with 8.

There are 8-1 spaces between the values in the original list and and 20-8 None values to distribute, so we can put a single None to every "space".

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7, None, 8]

Now we still have 12-7 None values to distribute and we can distribute 4 of those on every other space:

[1, None, None, 2, None, 3, None, None, 4, None, 5, None,None 6, None, 7, None,
    None, 8]

Now we have one left that we can assign randomly:

[1, None, None, 2, None, 3, None, None, 4, None, 5, None, None, 6, None, None 7, 
    None, None, 8]

Is there an algorithm that lets you fullfill a task like this? An implementation maybe?

like image 742
root Avatar asked Dec 09 '25 15:12

root


1 Answers

Basic idea: just linearly interpolate the new positions from the old positions. For simplicity, we use floor division, but you could get clever and use rounding division for a slightly more even distribution.

def stretch_to(l, n):
    out = [None] * n
    m = len(l)
    for i, x in enumerate(l):
        out[i*(n-1)//(m-1)] = x

    return out

Sample:

>>> stretch_to(range(8), 20)
[0, None, 1, None, None, 2, None, None, 3, None, 4, None, None, 5, None, None, 6, None, None, 7]
like image 93
nneonneo Avatar answered Dec 12 '25 08:12

nneonneo



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!