davecom / ClassicComputerScienceProblemsInPython

Source Code for the Book Classic Computer Science Problems in Python
https://www.manning.com/books/classic-computer-science-problems-in-python?a_aid=oaksnow&a_bid=d326fe0b
Apache License 2.0
1.03k stars 397 forks source link

No __hash__ override in class MCState (Chapter2) #14

Closed sun1991 closed 4 years ago

sun1991 commented 4 years ago

In Chapter2/generic_search.py, if an object is used in Set or Dict, shouldn't it implement its own __hash__?

For example: generic_search.py

def bfs(initial: T, goal_test: Callable[[T], bool], successors: Callable[[T], List[T]]) -> Optional[Node[T]]:
    ...
    # explored is where we've been
    explored: Set[T] = {initial}

missionaries.py

class MCState:
    ...

I don't see MCState implement its __hash__, which means by default, all objects will compare unequal except with themselves?

davecom commented 4 years ago

Yes, this is actually mentioned on page 50 as a justification for why we use bfs() to solve the problem "This solution uses bfs() (because using dfs() would require marking referentially different states with the same value as equal, and astar() would require a heuristic)."

It is also alluded to in exercise 3 at the end of Chapter 2; you'll see that implementing hash() is mentioned. It's convenient that it works for 3/3 with bfs(), but would require hash() to be robust for other algorithms/scenarios. You're right this should arguably be more explicit in a future edition. Thanks for bringing it up.