我的代码生成了所有2**40个可能的二进制数,从这些二进制数中,我将尝试得到所有符合我的objectif函数条件的向量,即:
1-矩阵中的每个向量必须有20个1。
2 s = s + (the index of one +1)* the rank of the one
的和必须等于4970。你知道吗
我写了这段代码,但它将需要很多时间,也许几个月,给结果。现在,如果可能的话,我正在寻找另一种方法或者对代码进行优化。你知道吗
import time
from multiprocessing import Process
from multiprocessing import Pool
import numpy as np
import itertools
import numpy
CC = 20
#test if there is 20 numbers of 1
def test1numebers(v,x=1,x_l=CC):
c = 0
for i in range(len(v)):
if(v[i]==x):
c+=1
if c == x_l:
return True
else:
return False
#s = s+ the nth of 1 * (index+1)
def objectif_function(v,x=1):
s = 0
for i in range(len(v)):
if(v[i]==x):
s = s+((i+1)*nthi(v,i))
return s
#calculate the nth of 1 in a vecteur
def nthi(v,i):
c = 0
for j in range(0,i+1):
if(v[j] == 1):
c+=1
return c
#generate 2**40 of all possible binray numbers
def generateMatrix(N):
l = itertools.product([0, 1], repeat=N)
return l
#function that get the number of valide vector that match our objectif function
def main_algo(N=40,S=4970):
#N = 40
m = generateMatrix(N)
#S = 4970
c = 0
ii = 0
for i in m:
ii+=1
print("\n count:",ii)
xx = i
if(test1numebers(xx)):
if(objectif_function(xx)==S):
c+=1
print('found one')
print('\n',xx,'\n')
if ii>=1000000:
break
t_end = time.time()
print('time taken for 10**6 is: ',t_end-t_start)
print(c)
#main_algo()
if __name__ == '__main__':
'''p = Process(target=main_algo, args=(40,4970,))
p.start()
p.join()'''
p = Pool(150)
print(p.map(main_algo, [40,4970]))
而您可以在readability中做很多改进,使代码更具python风格。你知道吗
我建议您使用numpy,这是处理矩阵的最快方法。 避免在“逐像素”循环中使用矩阵。使用numpy,您可以使这些计算更快,同时处理所有数据。 numpy还支持快速生成矩阵。我认为可以用更少的代码行和更快的速度生成一个随机的[0,1]矩阵。 另外,我建议您安装OPENBLAS、ATLAS和LAPACK,这使得线性代数的计算速度更快。你知道吗
我希望这对你有帮助。你知道吗
相关问题 更多 >
编程相关推荐