我想在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