在有序列表中的点之前,之后和之间计数

时间:2015-07-21 02:07:19

标签: python algorithm

我试图创建一个算法,它将在有序列表中的某些点之前,之后和之间计算几个计数。在这里,我的"某些要点"是需要附加到x值和有序的y值。以下是我试图做的简单说明。

x = [2,3,5,6,7,9]
y = [1,4,10]

# appending y to x and ordering gives us: 
full_list = [1,2,3,4,5,6,7,9,10]

因此,对于y = 1,通过将full_list切片为非编程方式计算度量标准:

num_between_before = len(full_list[0:0])
0
num_between_after = len(full_list[0:4])
2
num_before = len(full_list[0:0])
0
num_after = len(full_list[0:9])
8

但当然我试图以编程方式为任何列表x执行此操作,这些列表始终是数字,任何列表y也始终是数字。 x和y都可以是任何大小,但len(y)

以编程方式输出可能如下所示:

# y_val: (num_between_before, num_between_after, num_before, num_after)
output:
1:  (0, 2, 0, 8)
4:  (2, 4, 3, 5)
10: (4, 0, 8, 0)

显然我到目前为止在我的代码中遇到了麻烦:

x = [1434684599341,1434684606154,1434684607190,1434684613843,1434684677605,
     1434684704358,1434684708727,1434684724495,1434684758413,1434684782632]

y = [1434471725039, 1434684613844, 1434684708728, 1434684782633]

y.sort()

for i in y:
    x.append(i)

x.sort()

idx = []
for j in y:
    idx.append(x.index(j))   

counter = 0

for i, k in zip(idx, y):

    counter += 1
    if i == 0:
        before = len(x[i:i])
        after = len(x[i:conv_index[counter]]) - 1
        print before, after
    elif i == idx[-1]:
        before = len(x[i-counter:idx[counter-1]]) - 1
        after = len(x[i:i])
        print before, after
    else:
        before = len(x[i:idx[counter]])
        after = len(x[i:idx[counter]]) - 1
        print before, after

2 个答案:

答案 0 :(得分:1)

如果我关注你,我认为这有效:

def allCounts(x,y):
    z = x+y
    z.sort()
    d = {}
    for i in y:
        d[i] = z.index(i)
    counts = {}
    for i,j in enumerate(y):
        if i == 0:
            counts[j] = (0,d[y[i+1]]-d[j]-1,d[j],len(z)-d[j]-1)
        elif i < len(y) - 1:
            counts[j] = (d[j]-d[y[i-1]]-1,d[y[i+1]]-d[j]-1,d[j],len(z)-d[j]-1)
        else:
            counts[j] = (d[j]-d[y[i-1]]-1,0,d[j],len(z)-d[j]-1)
    return counts

使用您的测试数据:

>>> x = [2,3,5,6,7,9]
>>> y = [1,4,10]
>>> c = allCounts(x,y)
>>> c
{1: (0, 2, 0, 8), 10: (4, 0, 8, 0), 4: (2, 4, 3, 5)}

答案 1 :(得分:0)

您可以使用bisect_leftbisect_right来获取必要的索引:

#!/usr/bin/env python
from bisect import bisect
x = [2,3,5,6,7,9]; x.sort()
y = [1,4,10]; y.sort()

# appending y to x and ordering gives us:
z = sorted(x + y)
x_indices = [0] + [bisect(x, yy) for yy in y] + [len(x)]
z_indices = [1] + [bisect(z, yy) for yy in y] + [len(z)]
for i, yy in enumerate(y):
    print('{}: {}'.format(yy, (x_indices[i+1] - x_indices[i],
                               x_indices[i+2] - x_indices[i+1],
                               z_indices[i+1] - z_indices[0],
                               z_indices[-1] - z_indices[i+1])))

输出

1: (0, 2, 0, 8)
4: (2, 4, 3, 5)
10: (4, 0, 8, 0)