0

什么是创建维度为 N 的所有向量集的优雅方法,每个元素都是介于 0 和 K 之间的整数([0,K])。

我当前的代码是:

def nodes_init(n, k):
    nodes = {}
    e = np.identity(n)
    nodes[tuple(np.zeros(n))] = 0
    s = Set()
    s.add(tuple(np.zeros(n)))
    s_used = Set()
    while len(s) != 0:
        node = s.pop()
        if node in s_used:
            continue
        s_used.add(node)
        for i in xrange(len(e)):
            temp = node + e[i]
            temp = cap(temp, k)
            temp = tuple(temp)
            nodes[temp] = 0
            if not temp in s_used:
                s.add(temp)
    return nodes

def cap(t, k):
    for i in xrange(len(t)):
        if t[i] > k:
            t[i] = k
    return t

我不喜欢它。字典的键nodes是所需的向量。

4

1 回答 1

2

使用迭代工具

from itertools import product

def nodes_iter(n, k):
    """ returns generator (lazy iterator) rather than creating whole list """
    return product(range(k+1),repeat=n)

示例用法:

for node in nodes_iter(3,1):
    print node


(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
于 2012-04-22T19:37:24.117 回答