Last active
December 22, 2015 23:29
-
-
Save eidas/6547573 to your computer and use it in GitHub Desktop.
PyCon2013 チュートリアル アニマル問題その1
推論のみで学習しない時
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
# coding:utf-8 | |
import sys | |
def line_input(prompt): | |
while True: | |
sys.stdout.write(">>> %s : " % prompt) | |
sys.stdout.flush() | |
answer = sys.stdin.readline().strip() | |
if answer != "": | |
return answer | |
print(">>> 何も入力していないようですが...") | |
def input_yes_no(prompt): | |
while True: | |
answer = line_input("%s (yes/no)" % prompt).lower() | |
try: | |
return {"yes":True, "no":False}[answer] | |
except KeyError as exc: | |
print(">>> yes か no で答えてね") | |
def inference(node): | |
if type(node) is str: | |
return node | |
elif type(node) is list: | |
answer = input_yes_no("それは「%s」?" % node[0]) | |
if answer is True: | |
return inference(node[1][0]) | |
else: | |
return inference(node[1][1]) | |
else: | |
return None | |
#knowledge = ["哺乳類", ["くじら", "蛇"]] | |
#knowledge = ["哺乳類", [["ニャーと鳴く", ["猫", ["ワンと鳴く",["犬", "くじら"]]]], "蛇"]] | |
knowledge = ["哺乳類", | |
[ | |
["ニャーと鳴く", | |
["猫", | |
["ワンと鳴く", | |
["犬", "くじら"] | |
] | |
] | |
], "蛇" | |
] | |
] | |
def main(): | |
result = inference(knowledge) | |
if result is not None: | |
print(">>> 答えは「%s」!" % result) | |
else: | |
print(">>> 頭が混乱しております。") | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment