HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Checking a word grid

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordcheckinggrid

Problem

I wrote this program where you can input x amount of words that of length x that checks if the grid formed is the same words vertically as they are horizontally:

F I L E
I C E D
L E A D
E D D Y


The words can be entered in any order and the letters must stay in the same order. i.e. F I L E can't be F E L I

The permutations part of my code is so I can get all permutations of the words to check if they work in a grid

This feels very clunky and I'd like to slim it down. Does anyone have any suggestions?

import sys
import itertools
numWords = int(raw_input('Enter Number of Words: '))
words = []
stuff = []
for i in range(numWords):
    word = raw_input('Enter Word: ')
    if len(word) != numWords:
        print('Not Valid Grid')
        sys.exit()
    words.append(word)

stuff = list(itertools.permutations(words))
for i in range(len(stuff)):
    count = 0
    for j in range(0,4):
        s = ''
        for k in range(0,4):
            if stuff[i][j][k] == stuff[i][k][j]:
                s += stuff[i][k][j]
                if s in stuff[i]:
                    count += 1
    if count == numWords:
        for l in stuff[i]:
            print l
        sys.exit()
print('Not a Valid Grid')

Solution

This problem statement is simply asking if the array is a symmetrical matrix, so lets explore making a function which checks that!

We want a function which checks an object for all the qualities of a symmetrical matrix. Because we like to reuse functions in future programs, we're gonna make this function robust.

It checks that the parameter is a 2d array of either tuples or lists, that the matrix is a square, and checks that element i,j is the same as element j,i.

def check_symmetrical(array2d):
    # Check that the array is a valid square matrix
    if not type(array2d) is list and not type(array2d) is tuple:
        return False
    for row in array2d:
        if (not type(row) is list) and (not type(row) is tuple):
            return False
        if not len(row) == len(array2d):
            return False
    # Check that the array is a valid symmetrical matrix
    for i in range(len(array2d)):
        for j in range(len(array2d)):
            if not array2d[i][j] == array2d[j][i]:
                return False
    # if no failures then it must be good!
    return True


Lets revisit your input code

numWords = int(raw_input('Enter Number of Words: '))


This line has the opportunity to crash our code. Never trust the user! Lets use the isdigit function to fix that up

num_words = raw_input('Enter Number of Words: ') 
if not num_words.isdigit():
    print('Not a Valid Number')
    sys.exit()
num_words = int(num_words)


When a user input garbage, the program will close gracefully.

Now we need to turn that list of words into a 2d array. Lets use list comprehension

words = []
for i in range(num_words):
    word = raw_input('Enter Word: ')
    if len(word) != num_words:
        print('Not Valid Grid')
        sys.exit()
    words.append(word)
# comprehension used to create a list of lists
word_array2d = [list(word) for word in words]


Finally, run that array through our check_symmetrical function!

if check_symmetrical(word_array2d):
    print('Valid Grid')
else:
    print('Not a Valid Grid')

Code Snippets

def check_symmetrical(array2d):
    # Check that the array is a valid square matrix
    if not type(array2d) is list and not type(array2d) is tuple:
        return False
    for row in array2d:
        if (not type(row) is list) and (not type(row) is tuple):
            return False
        if not len(row) == len(array2d):
            return False
    # Check that the array is a valid symmetrical matrix
    for i in range(len(array2d)):
        for j in range(len(array2d)):
            if not array2d[i][j] == array2d[j][i]:
                return False
    # if no failures then it must be good!
    return True
numWords = int(raw_input('Enter Number of Words: '))
num_words = raw_input('Enter Number of Words: ') 
if not num_words.isdigit():
    print('Not a Valid Number')
    sys.exit()
num_words = int(num_words)
words = []
for i in range(num_words):
    word = raw_input('Enter Word: ')
    if len(word) != num_words:
        print('Not Valid Grid')
        sys.exit()
    words.append(word)
# comprehension used to create a list of lists
word_array2d = [list(word) for word in words]
if check_symmetrical(word_array2d):
    print('Valid Grid')
else:
    print('Not a Valid Grid')

Context

StackExchange Code Review Q#97048, answer score: 8

Revisions (0)

No revisions yet.