python - 查找总和为零的向量集

标签 python arrays performance numpy sum

我有 4 个数组(set1、set2、...),每组 3 个数组。例如

set1 = [array([1, 0, 0]), array([-1, 0, 0]), array([0, 1, 0]), ...]

我需要找出有多少向量组合总和为零。解决这个问题的简单方法是:

for b1 in set1:
  for b2 in set2:
    for b3 in set3:
      for b4 in set4:
        if all(b1 + b2 + b3 + b4 == 0):
          count = count + 1

但是,这是 O(n^4),基于 3sum 算法,我假设我可以做到 O(n^3),速度非常重要。关于如何在 Python 中快速执行此操作的任何线索?

最佳答案

这个怎么样?

from numpy import array
def createset(min, max):
    xr = lambda: xrange(min, max)
    return [ array([x, y, z]) for x in xr() for y in xr() for z in xr() ]

set1 = createset(-3, 3)
set2 = createset(-2, 1)
set3 = createset(-4, 5)
set4 = createset(0, 2)

lookup = {}
for x in set1:
    for y in set2:
        key = tuple(x + y)
        if key not in lookup:
            lookup[key] = 0
        lookup[key] += 1

count = 0
for x in set3:
    for y in set4:
        key = tuple(-1 * (x + y))
        if key in lookup:
            count += lookup[key]

print count

想法是生成前两组的所有总和。然后,您生成最后两组的总和,并查看查找表中是否存在使它们的总和为 0 的键。

关于python - 查找总和为零的向量集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32659767/

相关文章:

python - 在 if 中定义变量

python - 带参数的自定义激活

连接 C 字符串

ruby-on-rails - 如何在哈希数组中找到最大值?

php - 在 PHP MYSQL 中格式化 JSON 输出

python - 如何读取不同分辨率的图像以在 TensorFlow 中创建数据集

MySQL 查询在登台服务器上的运行速度比本地开发机器慢 5 倍

asp.net-mvc - ASP.Net MVC 和 14 条性能规则

c# - 什么更快,在字符串上切换还是在类型上切换?

python - 在 Python 中从控制台使用断点进行调试