如何在字谜中垂直查找字
问题描述:
我正在尝试编写一个接受字符(如纵横字谜)的二维(2D)列表和字符串作为输入参数的函数,该函数必须搜索二维列表中的列以查找单词的匹配。如果找到匹配项,函数应该返回一个包含匹配开始的行索引和列索引的列表,否则它应该返回值None。如何在字谜中垂直查找字
例如,如果函数被调用,如下图所示:
crosswords = [['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word = 'cat'
find_word_vertical(crosswords,word)
那么函数应该返回:
[1,0]
答
这一个是寻找水平......可帮助周围切换呢?
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
+0
任何人都可以帮助这个?我无法弄清楚自己的垂直部分... – bbubbletrubble
+0
感谢亚历山大,但我现在有这个想通了,会发布我的答案在这里,希望它可以帮助任何人。 –
答
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])
答
简单的版本是:
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])
这给正确的输出[1,0]
我不明白输出,为什么[1,0]? –
嗨,[1,0]的原因是因为搜索词是'猫',并且'cat'的第一个字母'c'的第一次出现在纵横字谜的索引1处并且在索引1的索引0处 –