问题
I'm trying to write a function that accepts a 2-dimensional (2D) list of characters (like a crossword puzzle) and a string as input arguments, the function must then search the columns of the 2D list to find a match of the word. If a match is found, the function should then return a list containing the row index and column index of the start of the match, otherwise it should return the value None.
For example if the function is called as shown below:
crosswords = [['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word = 'cat'
find_word_vertical(crosswords,word)
then the function should return:
[1,0]
回答1:
def find_word_vertical(crosswords,word):
columns = []
finished = []
for col in range(len(crosswords[0])):
columns.append( [crosswords[row][col] for row in
range(len(crosswords))])
for a in range(0, len(crosswords)):
column = [crosswords[x][a] for x in range(len(crosswords))]
finished.append(column)
for row in finished:
r=finished.index(row)
whole_row = ''.join(row)
found_at = whole_row.find(word)
if found_at >=0:
return([found_at, r])
回答2:
This one is for finding horizontal... could switching this around help?
def find_word_horizontal(crosswords, word):
list1=[]
row_index = -1
column_index = -1
refind=''
for row in crosswords:
index=''
for column in row:
index= index+column
list1.append(index)
for find_word in list1:
if word in find_word:
row_index = list1.index(find_word)
refind = find_word
column_index = find_word.index(word)
ret = [row_index,column_index]
if row_index!= -1 and column_index != -1:
return ret
回答3:
The simple version is:
def find_word_vertical(crosswords,word):
z=[list(i) for i in zip(*crosswords)]
for rows in z:
row_index = z.index(rows)
single_row = ''.join(rows)
column_index = single_row.find(word)
if column_index >= 0:
return([column_index, row_index])
This gives correct output [1,0]
回答4:
To find a word vertically:
def find_word_vertical(crosswords,word):
if not crosswords or not word:
return None
for col_index in range(len(crosswords[0])):
str = ''
for row_index in range(len(crosswords)):
str = str + crosswords[row_index][col_index]
if temp_str.find(word) >= 0:
return [str.find(word),col_index]
回答5:
To find a word Horizontaly:
def find_word_horizontal(crosswords, word):
if not crosswords or not word:
return None
for index, row in enumerate(crosswords):
str = ''.join(row)
if str.find(word) >= 0:
return [index,str.find(word)]
来源:https://stackoverflow.com/questions/35755116/how-to-find-word-vertically-in-a-crossword