【发布时间】:2016-06-06 21:35:30
【问题描述】:
我借用了一些代码来计算数组的运行中位数。但是对于每个正在运行的数组,我想排除零值。下面是代码:
def RunningMedian(seq, M):
seq = iter(seq)
s = []
m = M // 2
# Set up list s (to be sorted) and load deque with first window of seq
s = [item for item in islice(seq, M)]
d = deque(s)
# Simple lambda function to handle even/odd window sizes
median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m]) * 0.5
# Sort it in increasing order and extract the median ("center" of the sorted window)
s.sort()
# remove zeros from the array
s = np.trim_zeros(s)
print s
medians = [median()]
for item in seq:
old = d.popleft() # pop oldest from left
d.append(item) # push newest in from right
del s[bisect_left(s, old)] # locate insertion point and then remove old
insort(s, item) # insert newest such that new sort is not required
s = np.trim_zeros(s)
print s
medians.append(median())
return medians
我正在测试代码,但它失败了。我的例子是a = np.array([5 2 0 9 4 2 6 8]),我把这个函数称为RunningMedian(a,3)。我想要的每个运行框是:
[2,5]
[2,9]
[4,9]
[2,4,9]
[2,4,6]
[2,6,8]
但是,在我调用上述函数后,它给出了:
[2, 5]
[2, 9]
[4, 9]
[2, 9]
[2, 6]
[2, 8]
而且它还返回错误的中值。
调用返回的中位数为:[5, 9, 9, 9, 6, 8]
谁能帮我解决这个问题?谢谢。
【问题讨论】: