python - 哈希挖掘多处理
问题描述
我正在尝试解决 python 中的挖掘问题。给定一个字符串s
和一个整数z
,我必须找到以零结尾的最小字符串n
,其中附加到. 我写了以下代码:sha256(sha256(x))
z
x
n
s
from hashlib import sha256
from multiprocessing import Pool
def solve(string, zeros, cores):
with Pool(cores) as p:
for i in range(cores):
result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)
return result
def sub_solve(s, z, n0, cores):
n = n0 - 1
d = ""
while d[:-z] != "0"*z:
n += cores
s1 = (s + str(n)).encode()
h1 = sha256(s1)
h2 = sha256(h1.digest())
d = h2.hexdigest()
if n % 100000 == 0:
print("%d: %s" %(n,d))
return n
调用solve
,它应该在不同的内核中执行并行调用string = s
,每个内核应该解决不同的问题。当其中一个工作进程解决问题时,整个池应终止工作。当我运行时,我得到这个输出:zeros = z
cores = number of cores to use
sub_solve
n
solve
>>> pow.solve("asd",2,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\user\Desktop\pow.py", line 7, in solve
result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 355, in apply_async
raise ValueError("Pool not running")
ValueError: Pool not running
我该如何解决这个问题?
解决方案
第一次迭代后,池由于回调而终止。因此,在下一次迭代中,没有运行池。要解决这个问题,您必须先运行循环,然后再使用with
语句。
即with
用循环交换语句,for
如下所示:
from hashlib import sha256
from multiprocessing import Pool
def solve(string, zeros, cores):
for i in range(cores):
with Pool(cores) as p:
result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)
return result
def sub_solve(s, z, n0, cores):
n = n0 - 1
d = ""
while d[:-z] != "0"*z:
n += cores
s1 = (s + str(n)).encode()
h1 = sha256(s1)
h2 = sha256(h1.digest())
d = h2.hexdigest()
if n % 100000 == 0:
print("%d: %s" %(n,d))
return n
推荐阅读
- c - 为什么这些定义在 C 中不合法?
- mysql - Mysql Batch 将大约 11 GB 的数据从一个表插入到另一个表
- c++ - k位数和N个元素的最快排序方法,k <<< N
- node.js - CORS 问题。我需要帮助来解决这个问题
- debian - mount:只有 root 可以使用“--types”选项(有效 UID 为 2000)
- elasticsearch - 如何在 Dataproc 中访问 SparkContext?
- python - 我想从网站中提取数据,然后将其显示在我的网页上
- json - 更改键值并打印更改后的值和原始值
- reactjs - 构建失败 - 检查您的构建输出,将反应应用程序部署到 heroku
- apache-flink - Ververica Flink 培训资料中的 ExpiringStateSolution 之谜