2012-06-25 37 views
0
#!/usr/bin/python 

import time 
from array import * 

THINKING = 0 
HUNGRY = 1 
EATING = 2 

class Philosopher: 
    def __init__(self): 
     self.ph = array('i',[1, 2, 3, 4, 5]) 
     self.sleeptime = array('i',[30, 30, 30, 30, 30]) 

    def initialization_code(self): 
     for i in range(self.ph.__len__()): 
      self.ph[i] = THINKING 

    def pickup(self,i): 
     self.ph[i] = HUNGRY 
     self.test(i) 
     if(EATING not in (self.ph[i])): 
      while(EATING not in (self.ph[i])): 
       time.sleep(self.sleeptime[i]) 

    def putdown(self,i): 
     self.ph[i] = THINKING 
     self.test((i+4)%5) 
     self.test((i+1)%5) 

    def test(self,i): 
     if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)): 
      self.ph[i] = EATING 

    def start_process(self): 
     for i in range(self.ph.__len__()): 
      self.pickup(i) 
      self.putdown(i) 


    def display_status(self): 
     for i in range(self.ph.__len__()): 
      if (self.ph[i] == 0): 
       print "%d is THINKING" % i+1 
      elif (self.ph[i] == 1): 
       print "%d is WAITING" % i+1 
      elif (self.ph[i] == 2): 
       print "%d is EATING" % i+1 

phil = Philosopher() 
phil.initialization_code() 
phil.start_process() 
phil.display_status() 

以上是我嘗試在python中實現dining哲學家問題的一段代碼。 當我運行這段代碼就說明我這個錯誤:TypeError:'int'類型的參數是不可迭代的

Traceback (most recent call last): 

File "dining.py", line 59, in <module> 

phil.start_process() 

    File "dining.py", line 43, in start_process  
    self.pickup(i)  
    File "dining.py", line 27, in pickup  
    self.test(i)  
    File "dining.py", line 38, in test  
    if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)): 
    TypeError: argument of type 'int' is not iterable 

任何人都可以請幫我在這,爲什麼會出這個錯誤。我搜索了它,但無法解決。 在此先感謝!

回答

6

您的等式產生整數。整數不能使用in

>>> 'foo' in 3 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: argument of type 'int' is not iterable 
1

我認爲你是一般使用:

in/not in 

不正確。它看起來像你試圖比較應該完成的整數

== 
!= 
> 
>= 
< 
<= 

運營商代替。

2

除了in的問題,它只能應用於迭代以及在其類定義中具有__contains__的對象,您可能會遇到下一個問題:您沒有並行化。所以,你要麼應該使用線程或更換

if(EATING not in (self.ph[i])): 
    while(EATING not in (self.ph[i])): 
     time.sleep(self.sleeptime[i]) 

線 - 這是一個死循環,因爲沒有一個設置EATING狀態。

或者您應該通過其他方式來完成時間安排,通過不斷檢查掛鐘時間或創建事件安排系統來處理必須完成的操作。

順便說一句:print "%d is THINKING" % i+1也被打破,因爲沒有()圍繞i+1%具有更高的優先級。

+0

此外,爲什麼'self.ph .__ len __()'而不是'len(self.ph)'? – glglgl

+0

感謝您的回覆,我已經遇到了這個錯誤,現在解決方案運行良好 – user1479198

相關問題