您可以使用经典的 Node 类定义树:
class Node:
def __init__(self, name, *children):
self.name = name
self.children = children
tree = Node("an animal",
Node("aquatic",
Node("a cephalapod",
Node("having 8 tentacles", Node("an octopus")),
Node("having 10 tentacles", Node("a squid"))
), Node("a whale",
Node("a baleen", Node("a baleen")),
Node("not a baleen", Node("a dolphin"))
)
), Node("a land animal",
Node("a mammal",
Node("a bird",
Node("able to fly", Node("a sparrow")),
Node("not able to fly",
Node("a piscivore", Node("a penguin")),
Node("not a piscivore", Node("an ostrich"))
)
), Node("not a bird",
Node("a carnivore", Node("a lion")),
Node("a herbivore",
Node("having leather", Node("a bovine")),
Node("not having leather",
Node("having wool", Node("a sheep")),
Node("not having wool", Node("a pig"))
)
)
)
), Node("an insect",
Node("a carnivore",
Node("able to fly", Node("a wasp")),
Node("not able to fly",
Node("having 6 legs", Node("an ant")),
Node("having 8 legs", Node("a spider"))
)
), Node("a herbivore",
Node("able to fly", Node("a bee")),
Node("not able to fly", Node("a termite"))
)
)
)
)
那么主代码就可以继续问题循环了:
node = tree
while node.children:
answer = "n"
for child in node.children[:-1]:
print("Is it {}? (y/n)".format(child.name))
answer = input()
if answer.lower() == "y":
break
if answer.lower() != "y":
child = node.children[-1]
node = child
print("It is {}".format(node.name))
尽管您的树是二叉树,但此代码预见到有超过 2 个孩子的可能性。当对选择第一个孩子的问题回答“否”时,它会问会导致第二个孩子的问题,......等等,直到只剩下一个孩子作为可能性:它不会问相应的问题,因为这是唯一的选择。