0

I am having a bit of troubles getting this part of my code to work, I need to find a way to count the amount of times than an H occurs in a row in a list, (H, H, H) would count as two occurrences. I feel like I'm getting somewhere but just can't get the j to count up.

list['H', 'H', 'T', 'H']
j = 0
n = 0
for letter in list:
    if list[n] == ['H'] and list[n+1] == ['H']:
        j = j + 1

print('it was this amount of times ' + str(j))

  • 1
    Please edit your question with clarification. How does `[h, h, h]` not count as 3 occurrences? – BTables Sep 21 '21 at 05:35
  • seems your code counts how many times H occurs consecutive. Look at this thread https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item – Tomer S Sep 21 '21 at 05:36
  • sorry I should be more clear, I am looking for an occurrence in the list where [ H, H] occurs so in other words, I am looking for H to occur back to back and count how many times this occurs – Logan Hepfner Sep 21 '21 at 05:38
  • What do you expect the count for this list : `['H', 'H', 'T', 'H', 'H', 'H']`? 2 or 3? – Bhagyesh Dudhediya Sep 21 '21 at 05:51

4 Answers4

1

You could use a regex for this:

len(re.findall("H(?=H)", "HHH"))

The trick is using lookahead to match the second H, but still allow it to be matched again.

Before you think "regex is overkill for this and hard to read," two counter variables, indexing, and math has a lot more places for something to go wrong.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
0

Try this

list= ['H', 'H', 'T', 'H']
j = 0
n = 0
for letter in list:
    if letter == 'H' and list[n+1] == 'H':
        j = j + 1

print('it was this amount of times ' + str(j))

Will give

it was this amount of times 3
0

Did not get how ('H', 'H', 'H') counted to 2, is it that you want to find how many consecutive H occurs after first H?
Try out this, just updated few parts of your code:

data = ['H', 'H', 'T', 'H']
j = 0

for index in range(len(data)-1):
    if data[index] == 'H' and data[index+1] == 'H':
        j = j + 1

print('it was this amount of times ' + str(j))    

Output:

it was this amount of times 1
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16
0

You could do something clever with zip and sum:

>>> data = ['H', 'H', 'T', 'H', 'H', 'H', 'T']
>>> sum(a == b == 'H' for a, b in zip(data[1:], data[:-1]))
3

Same thing with an index:

sum(data[i-1] == data[i] == 'H' for i in range(1, len(data)))
flakes
  • 21,558
  • 8
  • 41
  • 88