Skip to content

Instantly share code, notes, and snippets.

@eidas
Created September 13, 2013 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eidas/6547888 to your computer and use it in GitHub Desktop.
Save eidas/6547888 to your computer and use it in GitHub Desktop.
PyCon2013 チュートリアル アニマル問題その2 推論+学習
#! /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])
next_node = node[1][0 if answer is True else 1]
result = inference(next_node)
if result is not None:
if input_yes_no("わかった!それは「%s」でしょう?" % result) is True:
print(">>> やったね!")
return None
else:
new_animal_name = line_input("考えていた動物の名前を教えてください")
new_question = line_input("「%s」が「%s」と違うところはなんですか?" % (new_animal_name, result))
new_node = [new_question, [new_animal_name, result]]
node[1][0 if answer is True else 1] = new_node
print("覚えたぞ。今度は間違えないぞ。")
return None
else:
return result
else:
print(">>> 頭が混乱しております。")
return None
knowledge = ["哺乳類", ["くじら", "蛇"]]
def main():
while True:
print(knowledge)
print(">>> なにか1種類の動物を考えてくださいな")
inference(knowledge)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment