Haj Sai
Haj Sai

Reputation: 311

Count the number of times values appear next to eachother

I have a list that looks like:

['C', 'C', 'H', 'H', 'E', 'H', 'C', 'C', 'C', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'C']

and I want to be able to count the number of times one, two, or three H's appear next to each-other but not anything above this.

So in the above example, HHH appears 0 times, HH appears two times, and H appears once.

I've tried to build a for loop that iterates over current and previous position but I feel this is too long winded.

Upvotes: 0

Views: 603

Answers (2)

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

Something like this maybe? It print all the number H appear next to each other.

X = ['C', 'C', 'H', 'H', 'E', 'H', 'C', 'C', 'C', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'C']
from collections import Counter
def cnt(X,c):
    i = 0
    count = Counter()
    temp = 0 #temporary variable to store counter
    while i < len(X):
        if X[i] != c:
            i += 1
        else:
            while i < len(X) and X[i] == c: #keep looping until end of array or different character
                temp += 1
                i += 1
            count[temp] += 1
            temp = 0
    print(count)
cnt(X,'H')

#Counter({2: 2, 1: 1, 4: 1})

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61930

You could do something like this, using defaultdict and groupby:

from collections import defaultdict
from itertools import groupby

lst = ['C', 'C', 'H', 'H', 'E', 'H', 'C', 'C', 'C', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'C']

counts = defaultdict(int)
for _, group in groupby(lst):
    s = ''.join(group)
    if len(s) < 4:
        counts[s] += 1

print(counts)

Output

{'CC': 1, 'HH': 2, 'E': 1, 'H': 1, 'CCC': 1, 'C': 2}

The idea is to find the run of consecutive letters with groupby and store the count in a dictionary, in this case a defaultdict.

Upvotes: 2

Related Questions