+1 vote
in Programming Languages by (40.5k points)
How can I make a list strictly increasing or decreasing if there are some duplicates in the list?

E.g. a=[10,12,15,12,10,16,17,19,20]

This list has duplicate values. If I sort it, it will be in increasing or decreasing order but not strictly increasing or decreasing.

1 Answer

+2 votes
by (72.7k points)
selected by
 
Best answer

If you want to make your list strictly increasing or decreasing, you can randomly add a small value to the duplicate values.

Here is an example:

>>> import numpy as np

>>> a=np.asarray([10,12,15,12,10,16,17,19,20])

>>> a

array([10, 12, 15, 12, 10, 16, 17, 19, 20])

>>> a1=a[np.argsort(a)]

>>> a1

array([10, 10, 12, 12, 15, 16, 17, 19, 20])

>>> indxToChange = np.where(np.diff(a1) == 0)[0]+1

>>> indxToChange

array([1, 3])

>>> a2 = [v+np.random.random(1)[0]*1e-10 if k in indxToChange else v for k,v in enumerate(a1)]

>>> a2

[10, 10.000000000078382, 12, 12.000000000090862, 15, 16, 17, 19, 20]

I sorted the list in ascending order, found the index of the duplicate records, and then added a small value to those duplicates. Now my list is strictly increasing.

...