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

select the max element in an increasing (and restarting over) list

I have this list:

mylist = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 
          1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3]

The length of the list is : 38.

I want a new list with length: 32.

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

My new list will be:

new_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 
            1, 1, 2, 1, 1, 1, 2, 1, 2, 3]

So, the numbers represent different counts. The first 19 elements of the mylist are all 1. The 20 and 21 elements are 1 and 2. This means I had 2 counts.

I want to get rid of the 1 and keep only the 2 because I have 2 counts. The same goes to the next 1 and 2 elements and to the last 1, 2, 3 elements. There, I have a max count of 3.

If I try something like this:

new_list = []
for idx in range(len(mylist)-1):
    if mylist[idx] == 1:
        if mylist[idx + 1] > mylist[idx]:
            new_list.append(mylist[idx + 1])
        else:
            new_list.append(mylist[idx])

because I am only checking the current and next elements, I miss the last 3.

>Solution :

Providing the first element in mylist is less than 2 then:

mylist = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 
          1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
newlist = []

for x in mylist:
    if x > 1:
        newlist[-1] = x
    else:
        newlist.append(x)

print(newlist)
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