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))

4
  • 1
    Please edit your question with clarification. How does [h, h, h] not count as 3 occurrences? Commented Sep 21, 2021 at 5:35
  • seems your code counts how many times H occurs consecutive. Look at this thread stackoverflow.com/questions/2600191/… Commented Sep 21, 2021 at 5: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 Commented Sep 21, 2021 at 5:38
  • What do you expect the count for this list : ['H', 'H', 'T', 'H', 'H', 'H']? 2 or 3? Commented Sep 21, 2021 at 5:51

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I would also suggest a regex, however the title says 'for loop'
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

1 Comment

n+1 will always check the second element in this example.
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

Comments

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.