2015-03-24 59 views
-1

我工作的程序和問題問:錯誤在我的代碼:應該返回一個布爾值,但返回的<class「NoneType」>

The first two ints are a row and column, and the third and fourth ints are another row and column. The last parameter is a symbol board. Return True if the path from the first row and column cell to the second row and column cell, including those two cells, is not completely empty, and return False otherwise. You may assume that the rows and columns given will form a horizontal or vertical path, not a diagonal path.

我的代碼看起來像這樣

MIN_SHIP_SIZE = 1 
MAX_SHIP_SIZE = 10 
MAX_BOARD_SIZE = 10 
UNKNOWN = '-' 
EMPTY = '.' 
HIT = 'X' 
MISS = 'M' 

def is_occupied(row1, col1, row2, col2, symbol_board): 

    if row1 == row2: # Checks the condition if true 
     if col1 > col2: # Checks to see if column1 is greater than column 2 
      return coordinates_notempty(row1, col2, col1, symbol_board) 
     else: 
      return coordinates_notempty(row1, col1, col2, symbol_board) 
    elif col1 == col2: 
     if row1 > row2: 
      return coordinates_notempty(col1, row2, row1, symbol_board) 
     else: 
      return coordinates_notempty(col1, row1, row2, symbol_board) 

coordinates_notempty是一個輔助功能,看起來像這樣:

def coordinates_notempty(c, c2, c3, symbol_board): 
    for i in range(c2, c3): 
     if symbol_board[c][i] == EMPTY: 
      return False 
    return True 

當我在空閒運行代碼我得到的是S上的錯誤ays應該返回一個bool,但返回<class 'NoneType'>,但我不明白爲什麼。

當我修復語法錯誤後,仍然收到應該返回布爾值,但返回錯誤。有人建議增加一個else語句,當我做了

def is_occupied(row1, col1, row2, col2, symbol_board): 

    if row1 == row2: 
     if col1 > col2: 
      return coordinates_notempty(row1, col2, col1, symbol_board) 
     else: 
      return coordinates_notempty(row1, col1, col2, symbol_board) 
    elif col1 == col2: 
     if row1 > row2: 
      return coordinates_notempty(col1, row2, row1, symbol_board) 
     else: 
      return coordinates_notempty(col1, row1, row2, symbol_board) 
    else: 
     return True 

我收到一個錯誤,類型錯誤:列表索引必須是整數,而不是元組

+0

在Python中,true和false用「True」和「False」表示。他們必須大寫。 – Shashank 2015-03-24 21:49:43

+1

^我希望在此基礎上有一個NameError。請提供[MCVE](http://stackoverflow.com/help/mcve)。 – jonrsharpe 2015-03-24 21:50:34

+0

我看不出我怎麼可能更加和平 – JerryMichaels 2015-03-24 22:54:50

回答

-1

嘗試True而不是true同樣地,對於False

+0

雖然有必要修復程序,但這並沒有解決OP的直接問題。 – jonrsharpe 2015-03-24 21:59:16

1

撇開這個問題與truefalse別人發現,你is_occupied佔兩種可能性:row1 == row2col1 == col2。如果兩個都不是這樣,那麼你的程序沒有返回值而結束,你得到None

最後一件事。當您檢查某個特定元素是否等於EMPTY時,您的coordinates_notempty會有問題,但您從未定義過什麼EMPTY

+0

我到底會如何解決這個問題? – JerryMichaels 2015-03-24 22:33:35

+0

不知道你的符號板是什麼樣的,或者對於路徑有什麼要求,很難說。您假設從一個點到另一個點存在直線垂直(列是相同的)或水平(行是相同的)線。你得到的錯誤表明假設是錯誤的。基本上,你需要回答這個問題:如果你的兩點不落在水平或垂直線上?兩點之間只有一條路徑嗎? – paidhima 2015-03-24 23:33:07