我想在python中使用多线程技术在项目euler中解决Problem 8。python循环多线程
查找1000位数字中连续五位数字的最大积。该号码可以找到here。
我的方法是从原始列表中生成5个块,然后重复此过程5次,每个过程的起始索引右移一位。
这里是我的线程类
class pThread(threading.Thread):
def __init__(self, l):
threading.Thread.__init__(self)
self.l = l
self.p = 0
def run(self):
def greatest_product(l):
"""
Divide the list into chunks of 5 and find the greatest product
"""
def product(seq):
return reduce(lambda x,y : x*y, seq)
def chunk_product(l, n=5):
for i in range(0, len(l), n):
yield product(l[i:i+n])
result = 0
for p in chunk_product(num):
result = result > p and result or p
return result
self.p = greatest_product(self.l)
当我尝试创建5个线程,以覆盖在我原来的列表中的所有5位块,手动方法下面给出了正确的答案,与num
作为个位数的号码清单,我从文字解析:
thread1 = pThread(num)
del num[0]
thread2 = pThread(num)
del num[0]
thread3 = pThread(num)
del num[0]
thread4 = pThread(num)
del num[0]
thread5 = pThread(num)
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
def max(*args):
result = 0
for i in args:
result = i > result and i or result
return result
print max(thread1.p, thread2.p, thread3.p, thread4.p, thread5.p)
但是这并不能给出正确的结果:
threads = []
for i in range(0, 4):
tmp = num[:]
del tmp[0:i+1]
thread = pThread(tmp)
thread.start()
threads.append(thread)
for i in range(0, 4):
threads[i].join()
我做了什么错在这里?我对多线程很陌生,所以请温和。
提示:重写代码,而无需使用德尔,这将是很容易理解为什么它没有工作,为什么你原来的代码也是不正确的。另外,考虑到GIL,这个代码不可能以比单线程版本更快的速度运行。 – 2013-02-15 01:37:10
我已经重写了没有del的代码,是的,它打破了两个版本。我今天晚些时候再学习一遍。谢谢你的建议。 – 2013-02-15 01:47:37
线程这是严重矫枉过正。你可以在1行中用'max(reduce(op.mul,n_list [i:i + 5])为1行在xrange(1000)中)' – wim 2013-02-15 02:08:30