【问题标题】:Determine which combinations of vectors will sum to another vector确定哪些向量组合将与另一个向量相加
【发布时间】:2018-07-03 06:26:41
【问题描述】:

我正在使用 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) 上找到了一些信息,但它并不能完全满足我的要求,或者我不知道如何有效地使用它。

【问题讨论】:

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


    【解决方案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]])]
    

    【讨论】:

    • 感谢您提供的信息。是的,随着选择的增加,倍数将是积极的。关于您编写​​的代码,您有什么推荐的资源吗?我想我遵循,但想在使用它之前获得更扎实的理解。
    • 我自己做的,所以我不能给你任何具体的链接。我不能告诉你它是否是最佳的,但它似乎有效。
    猜你喜欢
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2017-10-25
    相关资源
    最近更新 更多