7/27
Part 2 of 7 · Count with messagesLearn and do
Answer your parent once the last answer is in
When an answer arrives, file it under the child that sent it: self.replies[from_id] = count. Then check whether you're done. You're done when every child has answered, which is len(self.replies) == len(self.children). Then your answer is 1 for yourself plus the children's counts, sent to your parent.
Put that check in one method, finish_if_done, and call it from two places:
- after each answer arrives,
- right after the asks go out. A machine with no children is done at that moment, so the leaf case needs no code of its own.
def finish_if_done(replies: dict[int, int], children: list[int]) -> int | None:
"""The answer to send up, or None while a child still owes one."""
if len(replies) < len(children):
return None
return 1 + sum(replies.values())
print(finish_if_done({3: 1}, [3, 4]), finish_if_done({3: 1, 4: 1}, [3, 4]), finish_if_done({}, []))
None 3 1
A machine answers exactly once. Before the last answer it sends nothing. After it, it sends one answer.
The editor holds Machine with the ask side written as ask_children. Write the answer branch of receive, and write finish_if_done so the machine answers its parent once every child is in.