gpt4 book ai didi

python-3.x - Jupyter 笔记本永远不会使用多重处理完成处理(Python 3)

转载 作者:行者123 更新时间:2023-12-02 02:26:05 26 4
gpt4 key购买 nike

enter image description here

Jupyter 笔记本

我基本上正在使用多处理模块,我仍在学习多处理的功能。我正在使用达斯蒂·菲利普斯的书,这个代码属于它。

import multiprocessing  
import random
from multiprocessing.pool import Pool

def prime_factor(value):
factors = []
for divisor in range(2, value-1):
quotient, remainder = divmod(value, divisor)
if not remainder:
factors.extend(prime_factor(divisor))
factors.extend(prime_factor(quotient))
break
else:
factors = [value]
return factors

if __name__ == '__main__':
pool = Pool()
to_factor = [ random.randint(100000, 50000000) for i in range(20)]
results = pool.map(prime_factor, to_factor)
for value, factors in zip(to_factor, results):
print("The factors of {} are {}".format(value, factors))

在 Windows PowerShell(不在 jupyter 笔记本上)上,我看到以下内容

Process SpawnPoolWorker-5:
Process SpawnPoolWorker-1:
AttributeError: Can't get attribute 'prime_factor' on <module '__main__' (built-in)>

我不知道为什么单元格永远不会结束运行?

最佳答案

看来 Jupyter Notebook 和不同 IDE 中的问题在于设计功能。因此,我们必须将函数(prime_factor)写入不同的文件并导入模块。此外,我们还必须注意调整。例如,就我而言,我已将该函数编码到一个名为 defs.py 的文件中

def prime_factor(value):
factors = []
for divisor in range(2, value-1):
quotient, remainder = divmod(value, divisor)
if not remainder:
factors.extend(prime_factor(divisor))
factors.extend(prime_factor(quotient))
break
else:
factors = [value]
return factors

然后在 jupyter 笔记本中我写了以下几行

import multiprocessing  
import random
from multiprocessing import Pool
import defs



if __name__ == '__main__':
pool = Pool()
to_factor = [ random.randint(100000, 50000000) for i in range(20)]
results = pool.map(defs.prime_factor, to_factor)
for value, factors in zip(to_factor, results):
print("The factors of {} are {}".format(value, factors))

这解决了我的问题

enter image description here

关于python-3.x - Jupyter 笔记本永远不会使用多重处理完成处理(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49417299/

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