Crossword vertical

2

Problem: Writes a function called find_word_vertical that accepts a list of 2 character dimensions and a string as input arguments. This function searches the columns of the two-dimensional list to find a word equal to the input word. If an equality is found, the function returns a list containing the index of the row and the index of the column where the beginning of the found word begins, otherwise returns the value None.

For example, with the following inputs:

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]

My solution:

def find_word_vertical(crosswords,word):
    num = len(crosswords)
    joinner = ''
    w = str()
    vert_cross = list()
    for i in range(num):
        w = joinner.join(vert_cross)
        if word in w:
            for let in w:
                if let == word[0]:
                    row_ind = w.find(let)
                    col_ind = i-1
                    return [row_ind, col_ind]
        for j in range(num):
            vert_cross.append(crosswords[j][i])

The output gives me None , but the correct answer would be [0, 1]

What's wrong with my code?

    
asked by anonymous 05.03.2016 / 23:00

1 answer

2

Your code is working for the word 'cat', but will not work if the word search is in the last column ('mkt', for example) because its comparison is being made in the next iteration of the column content)

Here is a suggested solution:

crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word='cat'

def find_word_vertical(cw,w):
    for i in range(len(cw)):
        wstr = ''.join([cw[j][i] for j in range(len(cw))])
        if wstr.find(w) != -1: 
            return (i,wstr.find(w))
    return (-1,-1)

print find_word_vertical(crosswords,word)

As a hint, there is the lib pprint which in this case helps the viewer in the interpreter:

>>> import pprint
>>> pprint.pprint(crosswords)
[['s', 'd', 'o', 'g'],
 ['c', 'u', 'c', 'm'],
 ['a', 'c', 'a', 't'],
 ['t', 'e', 't', 'k']]
>>> 
    
13.04.2016 / 20:49