Skip to content Skip to sidebar Skip to footer

Finding Word In A Matrix

I have a matrix file (which python reads like a list of lists) and I need to tell if a word from a different file appears in that matrix, in a given direction. for example: given t

Solution 1:

There already seem to be several partial answers to your question. While it would not be efficient, with some simple parsing of the directions you could easily chain together the following separate solutions to come up with an answer to your problem.

Solution 2:

Try this:

from itertools import chain
from collections import defaultdict

matrix= [['c', 'a', 'T', 'e'],
         ['o', 'a', 't', 's'],
         ['w', 'o', 't', 'e'],
         ['n', 'o', 'l', 'e']]
words = ['caT', 'cow', 'own', 'cat']

d = defaultdict(int)
for i in chain(matrix, list(zip(*matrix))): # list(zip(*matrix)) is for down directionfor word in words:
        if word in''.join(i):
            d[word] = d[word] + 1

The d will be your expected output. {'caT': 1, 'cow': 1, 'own': 1}

Post a Comment for "Finding Word In A Matrix"