Last active
May 1, 2021 19:39
-
-
Save Per48edjes/f2119c903b99d53342669b7dde8bc422 to your computer and use it in GitHub Desktop.
Counting longest runs of {0, 1} in binary NumPy array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Source: https://stackoverflow.com/questions/24342047/count-consecutive-occurences-of-values-varying-in-length-in-a-numpy-array/24343375#24343375 | |
def longest_runs_sim(n: int = 50) -> int: | |
# Random sequence where each n_i is element of {0, 1} | |
seq = np.random.randint(0, 2, n) | |
longest_runs = {1: None, 0: None} | |
for i, outcome in enumerate([~seq, seq]): | |
runs = \ | |
np.diff( # Diff of indices counts runs | |
np.where( | |
np.concatenate( # Checks if next value is different; if yes, then 1 | |
# Note: Concatenation deals with edge cases | |
([outcome[0]], outcome[:-1] != outcome[1:], [True]) | |
) | |
)[0] # Returns indices for whenever the value switches | |
)[::2] # Only return the diffs for the 1s | |
longest_runs[i] = runs.max() | |
# Longest runs (0s or 1s) | |
return max(longest_runs.values()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment