Finding number of duplicates only and only at the end of a numpy array

Viewed 86

I know how can I find the number of duplicates from a numpy array. However, I need to find the number of duplicates only at the end of the numpy array. Please see my example below:

Example input is as follows:

1995
1996
1996
1997
1998
1999
1999
1999

Desired output:

3

Thanks in advance!

3 Answers

Here's one way with np.minimum.accumulate -

np.minimum.accumulate(a[::-1]==a[-1]).sum()

Sample run -

In [64]: a
Out[64]: array([2, 1, 9, 0, 0, 0, 2, 1, 0, 0, 0, 0, 2, 1, 0, 9, 9, 9, 9, 9])

In [73]: np.minimum.accumulate(a[::-1]==a[-1]).sum()
Out[73]: 5

Another with argmin -

In [88]: (a[::-1]==a[-1]).argmin()
Out[88]: 5

For a corner case, if all elements are same, we might need one extra step to check for all matches on a[::-1]==a[-1] and return len(a) in that case. Or if the count is 0, which can't be the output, we will output len(a) instead.

My solution is as follows, however, I am sure that there is a more elegant solution in a line!

def get_numlastdups(my_nparray):
    numlastdups=0
    for i in range(2,len(my_nparray)):
        if my_nparray[-1]==my_nparray[-i]: numlastdups+=1
        else: break 
    return numlastdups
mylist = [1995,
1996,
1996,
1997,
1998,
1999,
1999,
1999]
s = 0
x = mylist[-1]
for i in mylist:
   if i == x: s+= 1
print(s)
Related