Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created March 1, 2013 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasballinger/5067194 to your computer and use it in GitHub Desktop.
Save thomasballinger/5067194 to your computer and use it in GitHub Desktop.
boggle state transitions for an n x n board I acknowledge it's a bad idea in the first place, but should I indent this?
def get_transitions(n):
"""Return a dictionary of array spots to neighbors for an nxn grid"""
return {initial_row*n + initial_col :
{row * n + col
for row in range(max(0, initial_row-1), min(n, initial_row+2))
for col in range(max(0, initial_col-1), min(n, initial_col+2))
if (row, col) != (initial_row, initial_col)}
for initial_row in range(n)
for initial_col in range(n)}
@darius
Copy link

darius commented Mar 1, 2013

Unsolicited refactor because I'm distractible:

def get_transitions(n):
    "Return a dictionary of array spots to neighbors for an nxn grid."
    def neighbors(row, col):
        return {at(to_row, to_col)
                for to_row in around(row)
                for to_col in around(col)
                if (to_row, to_col) != (row, col)}
    def at(row, col):
        return row * n + col
    def around(i):
        return range(max(0, i-1), min(i+2, n))
    return {at(row, col): neighbors(row, col)
            for row in range(n)
            for col in range(n)}

@thomasballinger
Copy link
Author

Nice! I was reaching for something like around, much clearer; thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment