1

How can I code a function that shows how many consecutive positive values there are starting from the end to the start of the arrays A, B, C. So array B has 2 positive consecutive values starting from the end 3,5 hence why resulting in the output of 2.

import numpy as np

A = np.array([2,5,44,-12,3,-5])
B = np.array([2,5,44,-12,3,5])
C = np.array([2,5,44,12,3,5])

Expected output:

0
2
6
0

3 Answers 3

1

You can find the index of the last negative value first, and then subtract it from the array length:

def count_trailing_positive(a):
    idx = np.flatnonzero(a < 0)        # find all indices of negative values
    if len(idx) > 0:
        return len(a) - idx[-1] - 1    # subtract last index from array length
    else:
        return len(a)

count_trailing_positive(A)
# 0
count_trailing_positive(B)
# 2
count_trailing_positive(C)
# 6
Sign up to request clarification or add additional context in comments.

Comments

1

You can use:

def count_last_pos(arr):
    d = (arr>0)[::-1]
    return (d.cumsum() * d.cumprod()).max()

count_last_pos(A)
# 0 
count_last_pos(B)
# 2
count_last_pos(C)
# 6

Comments

1

The cumulative minimum over a positiveness mask of the reversed array:

def num_consec_pos_from_end(arr):
    return np.minimum.accumulate(arr[::-1] > 0).sum()

where the arr[::-1] > 0 will give a boolean array and we need the number of Trues until a False. Since False compares less than True, minimum.accumulate will change to False once and for all if it sees one. Then we sum the resultant array i.e., sum the True values for the output,

to get

>>> num_consec_pos_from_end(A)
0

>>> num_consec_pos_from_end(B)
2

>>> num_consec_pos_from_end(C)
6

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.