samedi 7 janvier 2023

Python list element patterns

I have a VERY simple question.

Honestly, I'm so sorry to ask you this stupid question but I really don't know how to do this.

I have a list like this.

p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4]

The elements in the list are usually the repetition of either 2, 4, 1 or 2, 5, 1.

Sometimes, there are no 1 at the end of 2, 4 or 2, 5.

I want to put 3 in the new list where the 3 consecutive elements of 2, 4, 1 or 2, 5, 1 are.

2, 4, 1 -> 3
2, 5, 1 -> 3

And I want to put 2 in the new list where the elements of 2, 4 or 2, 5 are.

2, 4 -> 2
2, 5 -> 2

Also, if there is either 2, 4 or 2, 5 at the end of the last 2, 4, 1 or 2, 5, 1, I need to put 3.

[2, 4, 1, 2, 5, 1, 2, 5] ==> [3, 3, 3]

However, if there are more than 2 of either 2, 4 or 2, 5 in a row after 2, 4, 1 or 2, 5, 1, I want to put 2 in the list like below.

[2, 4, 1, 2, 5, 2, 5] ==> [3, 2, 2]

My simple code below doesn't give me 2 at the end of the new list. Why is that?

Actually, I altered my code a lot and I am not getting what I want...

Any help will be GREATLY appreciated!

new_list = []

p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4] 

#p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4, 2, 4]
#p = [2, 4]

for i in range(0, len(p)):

    if i <= len(p) - 3:
        
        if p[i] == 2 and p[i+1] >= 4:
                
            if p[i+2] !=1:
                
                new_list.append(2)
                
            elif p[i+2] == 1:
            
                new_list.append(3)

            
print(new_list)

Aucun commentaire:

Enregistrer un commentaire