gpt4 book ai didi

python - 如何在 while 循环中省略 it.combinations() 的一些结果

转载 作者:太空宇宙 更新时间:2023-11-03 14:18:35 27 4
gpt4 key购买 nike

下面是创建特定图表的代码片段:

           h=0
while len(added)<i+1:

g.add_node(z1+h*2)
g.add_node(z2+h*2)

good.append(z1+h*2)
good.append(z2+h*2)

for u in it.combinations(good, 8):
u1 = list(u)

# the rest of the code...

h=h+1

地点:

good=[] - 以自然数形式列出当前值 [0,1,2,3,4,5,...]。

z1, z2 - good=[] 列表中当前值中最大的偶数和奇数。

执行 while 循环,直到图的边缘满足条件为止。然而,在 while 循环的每个后续步骤中,后续的偶数和奇数都会被添加以满足条件。

问题是,在添加偶数和奇数之后,函数 it.combinations() 从头开始​​检查所有组合,包括那些已经检查过的组合。什么不必要地扩展了循环的操作。但是,我希望 while 循环的后续步骤仅使用包含新添加的值z1 + h*2z2 + h* 的组合2.

如何做到这一点?

最佳答案

您可以记住每个步骤中 it.combinations 的结果,并且在下一步中仅在 for 循环中迭代这些当前结果和先前结果的补集(差异)。我建议使用集合运算来快速计算补集。

h=0
previous_combinations = set()
while len(added)<i+1:

g.add_node(z1+h*2)
g.add_node(z2+h*2)

good.append(z1+h*2)
good.append(z2+h*2)

current_combinations = set(it.combinations(good, 8))

for u in current_combinations - previous_combinations:
u1 = list(u)
# the rest of the code...
h=h+1

previous_combinations = current_combinations

关于python - 如何在 while 循环中省略 it.combinations() 的一些结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094096/

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