gpt4 book ai didi

python - 使用 List Comprehension 和/或 map 避免嵌套 for 循环

转载 作者:行者123 更新时间:2023-11-28 20:57:48 25 4
gpt4 key购买 nike

几天来,我一直在努力研究如何优化(不仅让它看起来更好)包含条件的 3 个嵌套循环/em> 和一个函数调用。我现在拥有的是以下内容:

def build_prolongation_operator(p,qs):
'''
p: dimension of the coarse basis
q: dimension of the fine basis

The prolongation operator describes the relationship between
the coarse and fine bases:
V_coarse = np.dot(V_fine, I)
'''

q = sum(qs)

I = np.zeros([q, p])

for i in range(0, q):
for j in range(0, p):
for k in range(0, qs[j]):
# if BV i is a child of j, we set I[i, j] = 1
if i == f_map(j, k, qs):
I[i, j] = 1
break

return I

f_map 是:

def f_map(i, j, q):
'''
Mapping which returns the index k of the fine basis vector which
corresponds to the jth child of the ith coarse basis vector.
'''

if j < 0 or j > q[i]:
print('ERROR in f_map')
return None

result = j

for k in range(0, i):
result += q[k]

return result

在分析我的整个代码时,我发现 build_prolongation_operator 被调用了 45 次,f_map 被调用了大约 850 万次!!

这是图片:

picture

我曾尝试对列表理解和 map 做同样的事情,但没有任何运气。

这是 build_prolongation_operator 期望的输入示例:

p = 10
qs = randint(3, size=p)

最佳答案

我不知道基数和延长运算符,但您应该关注算法本身。在优化方面,这几乎总是合理的建议。

这可能是症结所在——如果不是,它可以帮助您入门:f_map 计算不依赖于 i,但您要为每个重新计算它i 的值。由于 i 的范围从零到 qs 中值的总和,因此您可以通过缓存结果来节省大量的重新计算;谷歌“python memoize”,它实际上会自己写。修复此问题,您可能已完成,无需任何微优化。

您需要足够的空间来存储 max(p) * max(qs[j]) 值,但是从您报告的调用次数来看,这应该不是什么大问题。

关于python - 使用 List Comprehension 和/或 map 避免嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52311755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com