确定向量的哪些组合将求和另一个向量

时间:2018-07-02 16:06:51

标签: python python-3.x vector linear-algebra

我正在使用Python 3尝试找到一组向量的线性组合将得出另一个向量。我正在使用numpy数组作为向量。

例如,我将有一个目标向量和包含所有可能的向量选择的矩阵“选择”:

targetvector0 = numpy.array([0, 1, 2])

choices = numpy.array([[0, 1, 0], [0, 0, 1], [0, 0, 2], [1, 1, 0]])

我需要一些能够返回所有可能组合及其整数倍数(需要将它们为整数倍数)的总和,而不考虑那些不符合要求的整数:

option1 = [[1], [2], [0], [0]]
option2 = [[1], [0], [1], [0]]

我在numpy.linalg.solve(x, y)上找到了一些信息,但是它并没有完全满足我的需求,或者我不知道如何有效地使用它。

1 个答案:

答案 0 :(得分:1)

我想您搜索的倍数都是正数。

您可以仔细增加倍数,研究所有结果不大于目标向量的组合。

import numpy as np


def solve(target_vector, choices):
    nb_choices, n = choices.shape
    factors = np.zeros((1, nb_choices), dtype=np.int)
    i = 0

    while True:
        if i == nb_choices - 1:
            return

        factors[0, i] += 1
        difference_to_target = factors.dot(choices) - targetvector

        found_solution = np.all(difference_to_target == 0)
        factors_too_high = np.any(difference_to_target > 0)

        if found_solution:
            yield factors.copy()

        if found_solution or factors_too_high:
            factors[0, :i + 1] = 0
            i += 1
            continue

        i = 0


targetvector = np.array([0, 1, 2])
choices = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 2], [1, 1, 0]])
print(list(solve(targetvector, choices)))
# [array([[1, 2, 0, 0]]), array([[1, 0, 1, 0]])]
相关问题