Reputation: 11
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))
Upvotes: 0
Views: 55
Reputation: 23634
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)))
Upvotes: 0
Reputation: 1856
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
Upvotes: 0
Reputation: 7576
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.
Upvotes: 1
Reputation:
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
Upvotes: 0