查找满足阈值关系的组合

时间:2015-09-02 03:05:46

标签: python loops combinations combinatorics python-collections

给定phithetan_1n_2的值,我需要找到所有可能的对(N_1,{{1} })符合以下标准:

N_2

在Python中执行此操作的最有效方法是什么?显然,我可以使用两个0 <= N_1 <= n_1 0 <= N_2 <= n_2 N_1 - phi * N_2 >= theta 循环 - 迭代forN_1的所有可能值(来自前两个条件),并仅保存满足最后一个条件的那些对 - 但这样效率会相当低。

2 个答案:

答案 0 :(得分:1)

您可以使用numpy和vectorization,类似下面的内容

$queryString = "?phone=" . create_query_string(array('ios','windows','android'));
$array = create_array_from_query_string(substr($queryString, 7));

function create_query_string($array) {

    return implode('&phone=', $array);
}

function create_array_from_query_string($queryString) {

    return explode('&phone=', $queryString);
}

对的输出示例

import numpy as np

phi = 0.5
theta = 1
n1 = 10
n2 = 20

N1 = np.random.randint(-100, 100, size=100)
N2 = np.random.randint(-100, 100, size=100)

N1 = N1[(N1 >= 0) & (N1 <= n1)]
N2 = N2[(N2 >= 0) & (N2 <= n2)]

a = N2 * theta + phi
res = N1.reshape(N1.shape[0], 1) - a.reshape(1, a.shape[0])

indices = np.argwhere(res >= 0)
pairs = zip(N1[indices[:,0]], N2[indices[:,1]])

每个@dbliss请求,这里是模块化版本及其测试

[(8, 3),
 (8, 6),
 (8, 5),
 (8, 1),
 (3, 1),
 (9, 3),
 (9, 8),
 (9, 8),
 (9, 6),
 (9, 5),
 (9, 6),
 (9, 6),
 (9, 5),
 (9, 8),
 (9, 1)]

答案 1 :(得分:0)

这有效:

import itertools

def _get_N_1_and_N_2(n_1, n_2, phi, theta):
    """Get the (N_1, N_2) pairs as defined in Griffith (1963).

    See Equation 3.

    Parameters
    ----------
    n_1 : integer
      Number of excitatory inputs.

    n_2 : integer
      Number of inhibitory inputs.

    phi : number
      Factor that captures the difference between excitatory and
      inhibitory synaptic efficiencies.

    theta : number
      Spike threshold.

    """
    N_1 = range(n_1 + 1)
    N_2 = range(n_2 + 1)
    possible_N_1_N_2 = itertools.product(N_1, N_2)
    N_1_N_2 = []
    for N_1, N_2 in possible_N_1_N_2:
        if N_1 - phi * N_2 >= theta:
            N_1_N_2.append((N_1, N_2))
    return N_1_N_2

我想我可以使用for语句使if循环变得非常混乱list。但是。 。 。 NAA。

以下是测试:

import nose.tools as nt

def test__get_N_1_and_N_2():

    # Figure 3A in Griffith, 1963, Biophy J.
    n_1 = 4
    n_2 = 0
    theta = 2
    phi = 1
    desired = [(2, 0), (3, 0), (4, 0)]
    actual = _get_N_1_and_N_2(n_1, n_2, phi, theta)
    nt.assert_list_equal(desired, actual)

    # Figure 3B.
    n_1 = 5
    n_2 = 1
    theta = 2
    phi = 2
    desired = [(2, 0), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1)]
    actual = _get_N_1_and_N_2(n_1, n_2, phi, theta)
    nt.assert_list_equal(desired, actual)