Home > Software engineering >  The current value is the maximum value in the most recent period
The current value is the maximum value in the most recent period

Time:06-26

l = [5,1,1,1,5,3,6], and the expected returned data is [0, 0, 0, 0, 3, 0, 6]. Compare from right to left, if it is greater than, it will count cumulatively; if it is less than or equal to, it will interrupt the accumulation and start the next counting.

[5,1,3,6], and returns [0,0,1,3]. 6 is the maximum value in the last 3 cycles, 3 is the maximum value in the last 1 cycle, and 1 is the maximum value in the last 0 cycle.

CodePudding user response:

If I understand well the logic, this looks like an expanding comparison:

pure python

l = [5,1,3,6]
out = [sum(l[i]>x for x in l[:i]) for i in range(len(l))]

pandas

l = [5,1,3,6]
s = pd.Series(l)

out = s.expanding().apply(lambda x: sum(x.iloc[:-1].le(x.iloc[-1]))).astype(int)
out.tolist()

numpy:

l = [5,1,3,6]
a = np.array(l)

out = np.tril(a[:,None]>a).sum(1)
out.tolist()

output: [0, 0, 1, 3]

CodePudding user response:

l = [5, 1, 1, 1, 5, 3, 6]
# l = [5, 1, 3, 6]

l.reverse(); out = []
for i in range(0,len(l)):
    acc = 0
    for j in range(i 1, len(l)):
        if l[i] > l[j]: acc  = 1
        else: break   # interrupt count
    out.append(acc)
out.reverse(); out

Gives required output:

[0, 0, 0, 0, 3, 0, 6]
  • Related