[英]How do i get words from rows and columns having letters?
doing an assignment and struck to this problem 做作业,解决了这个问题
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
'''
return word in board
but i am getting FALSE
但我越来越
FALSE
Thanks in advance 提前致谢
The python in
operator works a bit differently from how you're using it. python
in
运算符的工作方式与您使用它的方式有些不同。 Here are some examples: 这里有些例子:
>>> 'laughter' in 'slaughter'
True
>>> 1 in [1,6,5]
True
>>> 'eta' in ['e','t','a']
False
>>> 'asd' in ['asdf','jkl;']
False
>>>
As you can see, it's got two major uses: testing to see if a string can be found in another string, and testing to see if an element can be found in an array. 如您所见,它有两个主要用途:测试以查看是否可以在另一个字符串中找到一个字符串,以及进行测试以查看是否可以在数组中找到一个元素。 Also note that the two uses can't be combined.
另请注意,这两种用途无法结合使用。
Now, about solving your problem. 现在,关于解决您的问题。 You'll need some sort of loop
for
going through all of the rows one by one. 您需要某种循环
for
一遍遍所有行。 Once you've picked out a single row, you'll need some way to join
all of the array elements together. 一旦你选择了单行,你需要一些方法来
join
所有的数组元素在一起。 After that, you can figure out if the word is in
the board. 之后,您可以确定单词是否
in
面板中。
Note: this only solves the problem of searching horizontally. 注意:这仅解决了水平搜索的问题。 Dunno if that's the whole assignment.
Dunno,如果那是整个任务。 You can adapt this method to searching vertically using the
zip
function. 您可以使用
zip
功能使此方法适应垂直搜索。
Here's something to get you unstuck: 这里有一些让您解脱的东西:
def board_contains_word(board, word):
# check accross
for row in board:
return word in ''.join(row):
# try with board's rows and columns transposed
for row in zip(*board):
return word in ''.join(row):
return False
print board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
print board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'TO')
Hint: You could simplify things by using the any()
function. 提示:您可以使用
any()
函数简化事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.