Continued with the last post
Some readers reported that if using graph_search
to solve the NQueensProblem
provided in search.py, python will complain that:
<br />
TypeError: list objects are unhashable
Yes, you are doing perfectly right and the code itself is imperfect. As this point, you might want to make the List objective hashable. Inspired by the idea of Set and FrozenSet in Python, you would expect a frozen(x) function to make any mutable object immutable (and therefore hashable) [Or you can try to use tuple from beginning, but in the NQueensProblem
code, it uses .index
method, which is only suitable for List]. Unfortunately, this proposal (PEP-351) was [Continued with the last post
Some readers reported that if using graph_search
to solve the NQueensProblem
provided in search.py, python will complain that:
<br />
TypeError: list objects are unhashable
Yes, you are doing perfectly right and the code itself is imperfect. As this point, you might want to make the List objective hashable. Inspired by the idea of Set and FrozenSet in Python, you would expect a frozen(x) function to make any mutable object immutable (and therefore hashable) [Or you can try to use tuple from beginning, but in the NQueensProblem
code, it uses .index
method, which is only suitable for List]. Unfortunately, this proposal (PEP-351) was](http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/peps/pep-0351.html) Guido. Hence, we don’t have a unified way to convert any “state” to an immutable object and insert it in to “closed table”. One possible way to do this is to write your own State class and implement the __hashcode__
function. The other handy but awkward way is to convert the list to a tuple when insterting to the “closed table, i.e. edit Line 144 of search.py as:
if tuple(node.state) not in closed:<br />
closed[tuple(node.state)] = True
Here is a toy forzen function.
"""Toy function frozen which can convert mutable objects to immutable Author: Eric You XU. GPLv2 """ def frozen(x): """Return the immutable version of an object. """ if type(x) == type([]): return tuple(x) elif type(x) == type([]): raise "I can't froze dictionary object as they are very hot." # fill your type here else: return x
You can put it in to search.py and edit the Line 144 as:
if frozen(node.state) not in closed:<br />
colsed[
frozen
(node.state)] = True
Now the code looks much better.