English 中文(简体)
每一“新最高”清单中未加改动的数字
原标题:List of each "new maximum" given a list of unsorted numbers in Python

I m 寻找从某些原始数字清单中获取每个“新最高”和(或)每个“新最高”指数清单的绝佳途径。

For example, the desired result given a list [1.0, 3.0, 2.0, 3.0, 5.0, 4.0] would be the list [1.0, 3.0, 5.0] and/or the list of indexes [0, 1, 4].

做到这一点的一个简单办法是:

values = [1.0, 3.0, 2.0, 3.0, 5.0, 4.0]
result = [values[0]]

for val in values:
    if val > result[-1]:
        result.append(val)

print(result)  # [1.0, 3.0, 5.0]

然而,我更有兴趣了解这些类型的清单算法如何以权宜(如非中值一行)和效率(即使有如假定的模块)。

问题回答

Using pandas.Series.expanding (或, 同样,:

pd.Series(values).expanding().max().unique() # gives: array([1., 3., 5.])
pd.Series(values).cummax().unique() # gives: array([1., 3., 5.])

Using numpy.ufunc.accumulate (specifically on numpy.maximum):

np.unique(np.maximum.accumulate(values)) # array([1., 3., 5.])

但是,视此为你们的风格,只要你需要,你就能够简单地把你的守则束缚到一种功能中,它就成为一种线性功能。 因此,这也应当为你的需要而努力:

def cum_unique_max(values):
    if len(values) == 0:
        # decide what you want in case the input is empty
        return []
    
    result = [values[0]]
    for val in values[1:]:  #  starting from the second value
        if val > result[-1]:
            result.append(val)
    
    return result

values = [1.0, 3.0, 2.0, 3.0, 5.0, 4.0]
print(cum_unique_max(values)) # [1.0, 3.0, 5.0]




相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签