jeudi 25 août 2022

counting the number of consecutive repetitions

I have a list of elements :

list = ['green','green','red','blue','red','blue','yellow','white','black','yellow','white','black','red','green','yellow','black']

I want to group the consecutive repetitions, no matter what size they are. meaning that this is my desired output.

['green x2','red-blue-x2','yellow-white-black x2','red,'green','yellow','black']

I was able to achieve only a part of it with js, here's the code:

let repetition_count = 1
let repetition_list = []
list.forEach(element => {
    let prev_elem = list[index-1]
    if(element == prev_elem)
        {
            repetition_count++
            repetition_list.push(element)
        }
    else if(repetition_count>1){
            if(str.endsWith(repetition_list[0]+"-")){
                str = remove_last_word(str)
            }
            str+= repetition_list[0] + "x"+repetition_count+"-"
            repetition_count = 1
            repetition_list = []
        }
        str+= element+"-"
        index++;
    }
    

with some tweaks to the above code it produced the following output :

['green x2','red','blue','red','blue','yellow','white','black','yellow','white','black','red,'green','yellow','black']

now I don't know how to check more than one element for repetition.

I tried list comprehension with groupby (itertools) in python but it didn't work.

any suggestions?

Aucun commentaire:

Enregistrer un commentaire