考虑一系列抛硬币:1, 0, 0, 1, 0, 1,其中 tail = 0,head = 1。
期望的输出是序列:0, 1, 2, 0, 1, 0
输出序列的每个元素计算自最后一个头以来的尾数。
我试过一个幼稚的方法:
def timer(seq):
if seq[0] == 1: time = [0]
if seq[0] == 0: time = [1]
for x in seq[1:]:
if x == 0: time.append(time[-1] + 1)
if x == 1: time.append(0)
return time
问题:有没有更好的方法?
最佳答案
使用 NumPy:
import numpy as np
seq = np.array([1,0,0,1,0,1,0,0,0,0,1,0])
arr = np.arange(len(seq))
result = arr - np.maximum.accumulate(arr * seq)
print(result)
产量
[0 1 2 0 1 0 1 2 3 4 0 1]
为什么 arr - np.maximum.accumulate(arr * seq)
? 所需的输出似乎与整数的简单级数有关:
arr = np.arange(len(seq))
所以自然的问题是,如果 seq = np.array([1, 0, 0, 1, 0, 1])
并且预期结果是 expected = np.array ([0, 1, 2, 0, 1, 0])
,那么 x
的值是多少
arr + x = expected
自
In [220]: expected - arr
Out[220]: array([ 0, 0, 0, -3, -3, -5])
看起来 x
应该是 arr * seq
的累积最大值:
In [234]: arr * seq
Out[234]: array([0, 0, 0, 3, 0, 5])
In [235]: np.maximum.accumulate(arr * seq)
Out[235]: array([0, 0, 0, 3, 3, 5])
关于python - 计算自最后一个头以来的尾数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257141/