def find_word_horizontal(crosswords,word):
for rows in crosswords:
string=''.join(rows)
if word in string:
#finding index
row_index=crosswords.index(rows)
column_index=rows.index(word[0])
return [row_index,column_index ]
return None
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])
def capitalize_word_in_crossword(crosswords,word):
if find_word_horizontal or find_word_vertical is not True:
result = []
for w in crosswords:
for l in w:
if l in word:
result.append(l.upper())
else:
result.append(l)
return result
#return [[l.upper() if l in word else l for l in w] for w in crosswords]
crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word='cat'
print(capitalize_word_in_crossword(crosswords,word))
这是用于在填字游戏中查找特定单词的代码。
在这里,我开发了两个辅助函数来水平和垂直地查找单词。如果同时找到水平和垂直匹配,则仅返回水平匹配,并将二维列表中的匹配字符大写并返回列表。例如,在上面的代码中,它应该打印:
[['s','d','o','g'],['c','u','c','m'],['a','C','A','T'],['t','e','t','k']]
如果未找到匹配项,则此函数只返回原始的二维列表而不进行修改。
但我的代码会返回['s','d','o','g','C','u','C','m','A','C','A','T','T','e','T','k']
答案 0 :(得分:0)
def capitalize_word_in_crossword(crossword,word):
if not crossword or not word:
return None
word_find_horizontal_at= find_word_horizontal(crossword,word)
if word_find_horizontal_at:
for i in range(len(word)):
crossword[word_find_horizontal_at[0]][word_find_horizontal_at[1]+i]=crossword[word_find_horizontal_at[0]][word_find_horizontal_at[1]+i].upper()
return crossword
word_find_vertical_at= find_word_vertical(crossword,word)
if word_find_vertical_at:
for j in range(len(word)):
crossword[word_find_vertical_at[0]+j][word_find_vertical_at[1]]=crossword[word_find_vertical_at[0]+j][word_find_vertical_at[1]].upper()
return crossword
此代码给出了正确的结果。