2017-01-30 46 views
0

我正在開發一款遊戲的功能,如果單詞包含在電路板中,我會陷入必須返回的功能中。當它的假設爲True時,Python的shell返回一個False狀態。 這是我的身體funtion:這個身體功能有什麼問題?

def board_contains_word(board, word): 
    """ (list of list of str, str) -> bool 

Return True if and only if word appears in board. 
Precondition: board has at least one row and one column. 

>>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT') 
True 
""" 
for word_index in range(len(board)): 
    if word in board: 
     return True 
    return False 
+1

'爲word_index範圍內(LEN(板)):'什麼是'word_index'因爲你的'for'循環中使用它的意義呢? – roganjosh

回答

0

你有一個循環,但你忽略了循環計數器。您將每次迭代中的值設置爲word_index變量;你應該在循環中使用它。

你的另一個問題是,你總是在第一次迭代後返回。您的第二個return應該是外部的循環,以便它只在整個循環耗盡時才運行。但是,在Python中你應該幾乎不會遍歷範圍(len(something))。但是,在Python中,你幾乎不應該遍歷範圍(len(something))。通過這件事情本身總是重複:您正在尋找在名單列表的字符串

for word_list in board: 
    if word in word_list: 
     return True 
return False 
0

,蟒蛇不在列表遞歸,即使它沒有,你仍然無法找到它,因爲你有一個字符不是字符串列表:

def board_contains_word(board, word): 
    for element in board: # First Iterate each list in the board. 
     if word in ''.join(element): # Then join the list of characters to make a word and look for your desired word in it 
      return True 
    return False