任意数量嵌套循环的算法 - python

我试图找出一种算法来概括我的代码中参数的任意整数值,该参数在我的代码中控制嵌套的for循环数。我的代码看起来像

A = numpy matrix of dimension (n x m)

For i = 0:p
 For j = 0:q
  ...
   For l = 0:z

     X[counter] = A[0]*i + A[1]*j + ... + A[n]*l
     counter = counter + 1

X = numpy matrix of dimension (p*q*...*z x len(A[0]))

for循环的数量由任意整数控制。

感谢您的任何建议!

参考方案

如前所述,这将很快爆发。但是,您可以使用笛卡尔乘积迭代器:

import itertools
import numpy as np

# Create a list with ranges:
rngs=np.array([p,q,..,z])

#Initialize X empty
X = np.empty((rngs.prod(), A.shape[0]))

#Cycle over all cartesian products
for i,t in enumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i in range(len(t))])

测试数据:

A = np.random.randint(10, size=(10, 10))
A
array([[8, 5, 0, 2, 0, 4, 5, 5, 0, 9],
       [7, 0, 5, 9, 9, 4, 8, 2, 6, 8],
       [4, 3, 8, 5, 2, 5, 4, 8, 6, 1],
       [0, 5, 6, 5, 5, 0, 8, 5, 4, 9],
       [3, 3, 2, 6, 6, 9, 7, 7, 3, 3],
       [4, 0, 7, 2, 3, 2, 2, 4, 1, 2],
       [6, 2, 5, 9, 9, 9, 4, 7, 7, 3],
       [6, 3, 4, 9, 0, 3, 8, 1, 6, 8],
       [6, 5, 6, 0, 8, 7, 9, 0, 7, 4],
       [2, 1, 4, 1, 3, 8, 3, 3, 2, 9]])

rngs = np.random.randint(1, 5, size=10)
rngs
array([4, 2, 1, 2, 2, 3, 4, 4, 2, 4])

X = np.empty((rngs.prod(), A.shape[0]))

for i,t in enumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i in range(len(t))])

X
array([[  0.,   0.,   0., ...,   0.,   0.,   0.],
       [  2.,   1.,   4., ...,   3.,   2.,   9.],
       [  4.,   2.,   8., ...,   6.,   4.,  18.],
       ...,
       [ 86.,  44.,  64., ...,  64.,  63.,  97.],
       [ 88.,  45.,  68., ...,  67.,  65., 106.],
       [ 90.,  46.,  72., ...,  70.,  67., 115.]])

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

python-docx应该在空单元格已满时返回空单元格 - python

我试图遍历文档中的所有表并从中提取文本。作为中间步骤,我只是尝试将文本打印到控制台。我在类似的帖子中已经看过scanny提供的其他代码,但是由于某种原因,它并没有提供我正在解析的文档的预期输出可以在https://www.ontario.ca/laws/regulation/140300中找到该文档from docx import Document from…

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

Python:集群作业管理 - python

我在具有两个阶段的计算群集(Slurm)上运行python脚本,它们是顺序的。我编写了两个python脚本,一个用于阶段1,另一个用于阶段2。每天早上,我检查所有第1阶段的工作是否都以视觉方式完成。只有这样,我才开始第二阶段。通过在单个python脚本中组合所有阶段和作业管理,是否有一种更优雅/自动化的方法?我如何知道工作是否完成?工作流程类似于以下内容:w…