Find all the words posted on the Scrabble board.

Any idea: an easy and quick way to get all the words placed on a Scrabble board when the board is represented by a two-dimensional array of characters?

Thanks in advance

+3
source share
3 answers

This is similar to Arziom’s answer , but the fact is that the Scrabble board will contain spaces between words.

So, suppose your "2D character array" looks like this:

board = [['s','t','a','c','k',' ',' ',' '],
         ['p',' ',' ','a',' ','c',' ',' '],
         ['o','v','e','r','f','l','o','w'],
         ['o',' ','a','t',' ','a',' ','a'],
         ['n','o','t',' ',' ','m','a','t'],
         [' ',' ','e',' ',' ',' ',' ','e'],
         [' ',' ','r',' ',' ',' ',' ','r'],
         [' ','e','y','e','s',' ',' ',' ']]

You can do the following:

import itertools
rows = (''.join(row) for row in board)
columns = (''.join(column) for column in zip(*board))
words = [word for line in itertools.chain(rows,columns) for word in line.split() if len(word) > 1]

What gives:

['stack', 'overflow', 'at', 'not', 'mat', 'eyes', 'spoon', 'eatery', 'cart', 'clam', 'water']

We do the conversion of each row and column of characters to type strings 'not mat', and then using str.split()to drop the spaces to give us a list of words, dropping all that one letter long.

itertools.chain(), .

+5

, . O (n ^ 2), , .

+3

If I understand you correctly, you can also try using something like this:

a = [['w','o','r','d'],
     ['i','p','o','d'],
     ['k','u','a','k'],
     ['i','s','d','s']]

lines = (''.join(line) for line in a)
rows = (''.join(line) for line in zip(*a))

print list(lines)
print list(rows)
0
source

All Articles