-2

The code I have tried

rand_array2 = np.random.randint(0,3, size=1000)
rand_array2

Searching for a way that allows me to count the (1,1,2) Sequences in rand_array2 with a for a loop.

mhhabib
  • 2,975
  • 1
  • 15
  • 29
Tim1_998
  • 3
  • 2
  • 1
    Please refer [this](https://stackoverflow.com/help/how-to-ask) guide how to ask questions – Max Dec 08 '20 at 09:49
  • Does this answer your question (this is for mutliple sequences, but you can use just one)? [Find the row indexes of several values in a numpy array](https://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array) – Daniel F Dec 08 '20 at 10:07

2 Answers2

0

A possible solution could look like:

import numpy as np
rand_array2 = np.random.randint(0,3, size=1000) 
pattern = np.array((1,1,2))    
matches=0
for i in range(len(rand_array2)-len(pattern)+1):
    match = rand_array2[i:i+3]==pattern
    if match.all():
        matches+=1
matches
Martin
  • 71
  • 4
0

Try this approach. Here we loop through the range of the random array and match any sequences. This should work with any size of sequence as long as it's less than the length of the random array.

seq = (1, 1, 2)
arr = (1, 1, 2, 1, 3, 2, 3, 2, 1, 1, 2, 1)
count = 0
for i in range(len(arr) - len(seq) + 1):
    if seq == arr[i:i+len(seq)]:
        count += 1

Edit: was a bit late.

LTJ
  • 1,197
  • 3
  • 16