8 嵌套循环可能的组合
8 nested loop possible combination
我构建了一个程序,可以在这个等式中找到 8 个不同的常数:
a*40 +b*0 +c*3 +d*10 +e*10 +f*0 +g*9 +h*7.5 =292(+-5)
a*4 +b*7 +c*5 +d*3 +e*0 +f*0 +g*7 +h*0 =63(+-5)
a*0 +b*6 +c*3 +d*0 +e*0 +f*5 +g*7 +h*0 =85(+-5)
a*175 +b*50 +c*50 +d*75 +e*75 +f*50 +g*110 +h*50 =635(+-5)
使用蛮力 (a-h <=5)。
但这需要很长时间(我知道,我知道你不需要说)
我怎样才能加快这个过程?
基本上,这是我的代码。实际上我的程序有 4 个:
chofound=[]
konstanta=[5,5,5,5,5,5,5,5]
## konstanta=[10,0,5,8,2,0,4,
for h in range(0,5):
for g in range(0,5):
for f in range(0,5):
for e in range(0,5):
for d in range(0,5):
for c in range(0,5):
for b in range(0,5):
for a in range(0,5):
hasil= a*konstanta[0]+\
b*konstanta[1]+\
c*konstanta[2]+\
d*konstanta[3]+\
e*konstanta[4]+\
f*konstanta[5]+\
g*konstanta[6]+\
h*konstanta[7]
if (hasil>=(292-5) and hasil <=(292+5)):
asd=[a,b,c,d,e,f,g,h]
print ("found with config: {}".format(asd))
chofound.append(asd)
return chofound
有什么有效的方法可以在不使用暴力的情况下真正知道 a-h 吗?或任何使我的代码 运行 有效的算法?
我认为这会非常快,并且还可以为您提供所有良好的配置:
import numpy as np
from itertools import product
konstanta = np.array([5,5,5,5,5,5,5,5])
configs = np.array(list(product(range(5),repeat=8))) # big array: iterating over rows is equivalent to your 8 nested for loops
hasil = (konstanta*configs).sum(axis=1) # element wise multiplication followed by sum over rows
good_configs = configs[(hasil>=0) & (hasil<=10)] # keep only rows where `hasil` is in desired range
我构建了一个程序,可以在这个等式中找到 8 个不同的常数:
a*40 +b*0 +c*3 +d*10 +e*10 +f*0 +g*9 +h*7.5 =292(+-5)
a*4 +b*7 +c*5 +d*3 +e*0 +f*0 +g*7 +h*0 =63(+-5)
a*0 +b*6 +c*3 +d*0 +e*0 +f*5 +g*7 +h*0 =85(+-5)
a*175 +b*50 +c*50 +d*75 +e*75 +f*50 +g*110 +h*50 =635(+-5)
使用蛮力 (a-h <=5)。 但这需要很长时间(我知道,我知道你不需要说) 我怎样才能加快这个过程?
基本上,这是我的代码。实际上我的程序有 4 个:
chofound=[]
konstanta=[5,5,5,5,5,5,5,5]
## konstanta=[10,0,5,8,2,0,4,
for h in range(0,5):
for g in range(0,5):
for f in range(0,5):
for e in range(0,5):
for d in range(0,5):
for c in range(0,5):
for b in range(0,5):
for a in range(0,5):
hasil= a*konstanta[0]+\
b*konstanta[1]+\
c*konstanta[2]+\
d*konstanta[3]+\
e*konstanta[4]+\
f*konstanta[5]+\
g*konstanta[6]+\
h*konstanta[7]
if (hasil>=(292-5) and hasil <=(292+5)):
asd=[a,b,c,d,e,f,g,h]
print ("found with config: {}".format(asd))
chofound.append(asd)
return chofound
有什么有效的方法可以在不使用暴力的情况下真正知道 a-h 吗?或任何使我的代码 运行 有效的算法?
我认为这会非常快,并且还可以为您提供所有良好的配置:
import numpy as np
from itertools import product
konstanta = np.array([5,5,5,5,5,5,5,5])
configs = np.array(list(product(range(5),repeat=8))) # big array: iterating over rows is equivalent to your 8 nested for loops
hasil = (konstanta*configs).sum(axis=1) # element wise multiplication followed by sum over rows
good_configs = configs[(hasil>=0) & (hasil<=10)] # keep only rows where `hasil` is in desired range