2013-09-30 23 views
3

對不起,如果我不小心重複了一個問題,我仍然是Python的新手。python不到錯誤比較int和數組長度

我正在研究一個學校項目,該項目要求我們使用圖搜索來解決經典謎題。我正在用Python寫作,因爲這是我開始學習它的一個很好的藉口,但是我遇到了一些對我來說很陌生的問題。

對於一個節,我想循環遍歷探索節點列表,並查看是否有另一個節點與已探測節點列表中的節點相同。如果尚未探索,那麼它可能成爲圖中探索的下一個節點。

我發現的問題是在一行中,我做了一個for循環來搜索探索列表中的每個值。下面是我寫的:

def validate(self, testnode, explored): 
    if((testnode.wolf == testnode.sheep != testnode.farmer) or (testnode.sheep == testnode.cabbage != testnode.farmer)): 
     #return failure 
     return false 
    for i < len(explored): 
     if testnode == explored[i]: 
      #return failure 
      return false 
    else: return true 

,這裏是我的錯誤

File "AI_Lab1_BFS.py", line 54 
    for i < len(explored): 
     ^
SyntaxError: invalid syntax 

我已經閱讀那麼,這個問題是在比較錯誤的類型,像int比較與Python用戶其他一些問題浮動。我不認爲這是我的問題,因爲len(探索)應該是一個int,對嗎?這就是我所看到的,雖然也許我誤解/假設了事情。如果你能提供任何幫助,我將非常感激!

感謝大家的快速回復。建議的更改肯定有效。

+2

另外,/否則不要使用。這是很少使用,可能不會做你認爲它會。 –

回答

4

更換for i < len(explored):for i in range(0, len(explored)):

+0

應該是'範圍(0,len(探索))'?或者只是'範圍(len(探索))' – dckrooney

+0

@dckrooney:非常正確,感謝您的支持! –

+0

他們是一樣的吧? – justhalf

3

無效Python語法。實際上,這不是任何僞代碼中的有效聲明,因爲您需要i的起始值。假設上述值是0,你會想:

def validate(self, testnode, explored): 
    if((testnode.wolf == testnode.sheep != testnode.farmer) or (testnode.sheep == testnode.cabbage != testnode.farmer)): 
     #return failure 
     return false 
    for i in range(len(explored)): 
     if testnode == explored[i]: 
      #return failure 
      return false 
    else: return true 

,或者甚至更好:

def validate(self, testnode, explored): 
    if((testnode.wolf == testnode.sheep != testnode.farmer) or (testnode.sheep == testnode.cabbage != testnode.farmer)): 
     #return failure 
     return false 
    for node in explored: 
     if testnode == node: 
      #return failure 
      return false 
    else: return true 

順便說一下,還有其他一些問題與您的代碼:

  1. 更換truefalseTrueFalse
  2. testnode.wolf == testnode.sheep != testnode.farmer在你認爲它會做什麼,你應該打破,在使用elseand
  3. 避免與for加入兩條語句的方式不會表現:它的棘手(非直觀)

我的2美分:不要以困難的方式學習Python,因特網上有很多非常直觀的資源。我最喜歡的是http://pythonmonk.com/

0

你的具體情況,你也可以這樣做:

if testnode in explored: 
    return False 
return True