如何在填字游戏中垂直找到单词

时间:2016-03-02 18:19:30

标签: python-3.4

我正在尝试编写一个接受二维(2D)字符列表(如填字游戏)和一个字符串作为输入参数的函数,然后该函数必须搜索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]

5 个答案:

答案 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])

答案 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

答案 2 :(得分:0)

简单版本是:

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]

答案 3 :(得分:0)

要垂直查找单词:

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]

答案 4 :(得分:0)

要找到一个单词Horizo​​ntaly:

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)]