This really has nothing to do with printing. Your problem is here:
heapq.heappush(probs,f)
f
is an instance of your InternalNode
class, but the class doesn't define any ordering. Therefore Python defaults to ordering InternalNode
instances by memory address. This isn't at all what you want, and memory addresses vary depending on what else you do (print, run PDB, create or delete other objects ...).
The easiest fix is to add a __cmp__
method to your class:
def __cmp__(a, b):
return cmp(a.prob, b.prob)
Then the output will be consistent.
EDIT: hmm, you're also getting memory-address ordering for LeafNode
instances, so add a __cmp__
to that too.