Finding word in a matrix

∥☆過路亽.° 提交于 2019-12-11 17:04:34

问题


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 this matrix:

c,a,T,e
o,a,t,s
w,o,t,e
n,o,l,e

the words:

caT, cow, own, cat

and the directions:

downright (diagonal)

I expect an output:

cat:1

and for the direction:

down, right

I expect:

cow:1
own:1
cat:1

my function is set like so:

def word_finder(word_list,matrix, directions):

What I find hard to do is go through a list of lists and run over indexes that are horizontal for example or diagonal :( thx for the help


回答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.

  • Diagonal Traversal: In Python word search, searching diagonally, printing result of where word starts and ends
  • Linear Traversal: How to find words in a matrix - Python



回答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 direction
    for 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}



来源:https://stackoverflow.com/questions/53358280/finding-word-in-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!