Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert an initial list to other that considers a sequence of min and max values for each element of the initial list?

this is the list I have:

emissions=[30,50,20,70]

this is the list I would like to get:

f=[0,30,30,80,80,100,100,160)

such as:
f=[]
f[1]=emissions[0]
f[2]=emissions[0]
f[3]=emissions[0]+emissions[1]
f[4]=emissions[0]+emissions[1]
f[5]=emissions[0]+emissions[1]+emissions[2]
f[6]=emissions[0]+emissions[1]+emissions[2]
f[7]=emissions[0]+emissions[1]+emissions[2]+emissions[3]

I believe the answer must consider some loop but I cant figure out how

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use numpy.cumsum with append 0, numpy.repeat with remove first and last repetead values by indexing if performance is important in large lists:

f = np.repeat(np.cumsum([0] + emissions), 2)[1:-1].tolist()
print (f)
[0, 30, 30, 80, 80, 100, 100, 170]

np.random.seed(123)
emissions = np.random.randint(100, size=1000)

#Timeless solution
In [62]: %%timeit
    ...: cumsum = [0] + list(accumulate(emissions))
    ...: f = [x for pair in zip(cumsum, cumsum[1:]) for x in pair]
    ...: 
242 µs ± 21.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [63]: %%timeit 
    ...: np.repeat(np.cumsum([0] + emissions), 2)[1:-1].tolist()
    ...: 
60.3 µs ± 1.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading