8
Guido van Rossum
Last seen 8 years ago
Member for 11 years, 1 month, 2 days
Difficulty Normal
END = [[1,2,3],[4,5,6],[7,8,0]]
If you use a tuple of tuples intead of a list of lists to represent the
puzzle state, a number of things become easier: e.g. you can use the state
directly as a dict key rather than its str(), and you don't have to use
deepcopy() to create a modified state.
More
for col in range(len(a[0])):
If you rewrite these two loops as
for row, a_row in enumerate(a):
for col, a_row_col in enumerate(a_row):
you can use a_row_col instead of a[row][col] on the next line, which saves
a bunch of indexing.
More
pos = getPos(b,a[row][col])
Have you heard of tuple unpacking? If you write this as
target_row, target_col = getPos(b, a_row_col)
you can avoid indexing in the next line, using targer_row instead of pos[0]
and target_col instead of pos[1].
More
#get position of an element in an array
That's a pretty poor description. This function finds the (row, col)
position of an element in a puzzle state (represented as a 2-dimensional
array).
More
return (row,state[row].index(elem))
I'd rewrite this whole thing as follows:
for row, line in enumerate(state):
col = line.find(elem)
if col >= 0:
return row, col
That's one more line of code, but it's more readable and less wasteful
(your solutio
More
def getAdjNode(node):
I'd use 'adjacent' in full in the function name.
More
emptyPos= getPos(node.state,0)
I'd use tuple unpacking here again to give emptyPos[0] and empytyPos[1]
separate names, e.g.
empty_row, empty_col = getPos(node.state, 0)
More
for dir in DIRECTIONS.keys():
To iterate over the keys of a dict you can just write "for dir in
DIRECTIONS:" -- but in this case it's even better to iterate over the items:
for dir, (dir_row, dir_col) in DIRECTIONS.items():
More
for dir in DIRECTIONS.keys():
DIRECTIONS[dir][1])
Use tuple unpacking here too. Then this line can become:
new_row, new_col = empty_row + dir_row, empty_col + dir_col
and all uses of newPos[0] and newPos[1] below become just new_row and
new_col. Less indexing, more meaningful variabl
More
for dir in DIRECTIONS.keys():
len(node.state[0]) :
I'd compute the lengths once outside the loop.
More