Vertical crossword

Asked

Viewed 379 times

2

Problem: Write 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 in which the principle of the word found begins, otherwise it 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 must 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 way out gives me None, but the correct answer would be [0, 1]

What’s wrong with my code?

1 answer

2

Your code is working for the word 'cat', but it will not work if the word search is in the last column ('Mkt', for example) because your comparison is being made in the next iteration of the column (the first just append the content)

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

Taking advantage, as a hint, there is the lib pprint that in this case helps the visualization in the interpreter:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.