[英]Rounding values in list when using itertools.accumulate function
[英]compute suffix maximums using itertools.accumulate
計算整數序列的后綴最大值的推薦方法是什么?
以下是基於問題定義的蠻力方法( O(n**2)
時間):
>>> A
[9, 9, 4, 3, 6]
>>> [max(A[i:]) for i in range(len(A))]
[9, 9, 6, 6, 6]
使用itertools.accumulate()
一個O(n)
方法如下,它使用兩個列表構造函數:
>>> A
[9, 9, 4, 3, 6]
>>> list(reversed(list(itertools.accumulate(reversed(A), max))))
[9, 9, 6, 6, 6]
是否有更多的pythonic方式來做到這一點?
切片反轉使事情更簡潔,更少嵌套:
list(itertools.accumulate(A[::-1], max))[::-1]
盡管如此,它仍然是你想要捆綁到一個函數中的東西:
from itertools import accumulate
def suffix_maximums(l):
return list(accumulate(l[::-1], max))[::-1]
如果你正在使用NumPy,你需要numpy.maximum.accumulate
:
import numpy
def numpy_suffix_maximums(array):
return numpy.maximum.accumulate(array[::-1])[::-1]
我個人認為“Pythonic”我覺得“簡單易讀”,所以這是我的Pythonic版本:
def suffix_max(a_list):
last_max = a[-1]
maxes = []
for n in reversed(a):
last_max = max(n, last_max)
maxes.append(last_max)
return list(reversed(maxes))
對於它的價值,它看起來比itertools.accumulate
方法慢50%,但我們說的是25毫秒vs 17毫秒的100,000英尺的列表,所以它可能沒什么關系。
如果速度是最重要的,並且您期望看到的數字范圍明顯小於您正在使用的列表的長度,則可能值得使用RLE :
def suffix_max_rle(a_list):
last_max = a_list[-1]
count = 1
max_counts = []
for n in a_list[-2::-1]:
if n <= last_max:
count += 1
else:
max_counts.append([last_max, count])
last_max = n
count = 1
if n <= last_max:
max_counts.append([last_max, count])
return list(reversed(max_counts))
對於在0-10000范圍內的100,000個int的列表,這比上述方法快大約4倍,並且比itertools方法快大約2.5倍。 再次提供的是,您的數字范圍明顯小於列表的長度,也會占用更少的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.