Home > Net >  How to find back to back same items in Python?
How to find back to back same items in Python?

Time:09-21

I basically want to count how many times "H" printed back to back 3 times in this random sequence. How can i add a code which detects its occurence, is it possible with index method?

import random
prob= ["H","T"]
streakcount=0
x =[]
for excount in range(1000):
  y = random.choice(prob)
  x.append(y)
print(x)

CodePudding user response:

Yeah, you can index the previous element in the 'x' array and check if it is also an 'H'.

So, first add an IF statement after y is assigned a random value and check if that value is 'H'. If it is, then you want to index the previous element in the array 'x' to see if it is also an 'H'. Finally, we need an accumulator to store the number of times this happens.

That's the gist of it. The only potential hiccup we want to avoid occurs at the very beginning of the 'for' loop when excount is 0 or 1. At this time, if an 'H' is randomly chosen and we try to index the 'x' array at the index, excount-2, we'll end up indexing the list from the end (with a negative number) or indexing a list at an index that does not yet exist. This could occur because we're subtracting 1 and 2 from excount and then indexing the 'x' array, so we just want to double-check that excount is >= 2 before we start checking to see if we've seen three H's in a row.

import random
prob= ["H","T"]
streakcount=0
x =[]
for excount in range(1000):
  y = random.choice(prob)
  if y == 'H' and excount >= 2:
    # check to see if previous element was also an 'H'
    if x[excount-1] == 'H' and x[excount-2] == 'H':
       streakcount  = 1    # 3 H's in a row! increment counter
  x.append(y)
print(x)

CodePudding user response:

I think you can just convert a list to string and then use count to get count.

import random
prob= ["H","T"]
streakcount=0
x =[]
for _ in range(1000):
   y = random.choice(prob)
   x.append(y)
strlist = ' '.join(map(str, x))
print(strlist.count("H H H"))

CodePudding user response:

The deque class from the collections module is useful for this use-case. The deque is constructed so as to support a list with a maximum size of 3. As new values are appended to the deque the oldest value is lost. Therefore we can use the deque's count() function to get the number of values matching the criterion of interest

from random import choice
from collections import deque

ht = ['H', 'T']

streakcount = 0
d = deque([], 3)

for _ in range(1_000):
    d.append(choice(ht))
    if d.count('H') == 3:
        streakcount  = 1

print(f'{streakcount=}')

CodePudding user response:

import random

prob = ["H", "T"]
streakcount = 0
x = []
for excount in range(1000):
    y = random.choice(prob)
    x.append(y)

for i in range(len(x)):
    if i > 0 and i   1 <= len(x):
        if x[i - 1] == 'H' and x[i] == 'H' and x[i   1] == 'H':
            streakcount  = 1

print(streakcount)
  • Related