Calvin (Deutschbein)
W12Fri: 15 Nov
Identifying name for first question Text of first question ------ responseA: name of next question responseB: name of next question responseC: name of next question responseD: name of next question ...more questions/answers... |
RemQ1 What is the value of 17 % 4? a. 0 b. 1 c. 3 d. 4 ------ a: RemQ2 b: PrecQ1 c: RemQ2 d: RemQ2 |
|
|
from TMCourse import read_course
def teaching_machine():
course = choose_course()
course.run()
def choose_course():
# Returns a course chosen by the user.
while True:
try:
filename = input("Enter course name: ")
with open(filename + ".txt") as f:
return read_course(f)
except IOError:
print("Please enter a valid course name.")
from TMQuestion import TMQuestion, read_question
class TMCourse:
def __init__(self, questions):
# New TMCourse object with the specified questions.
self._questions = questions
def get_question(self, name):
# Returns the question with the specified name.
return self._questions[name]
def run(self):
# Steps through the questions in this course.
current = "START"
while current != "EXIT":
question = self.get_question(current)
for line in question.get_text():
print(line)
answer = input("> ").strip().upper()
next = question.lookup_answer(answer)
if next is None:
print("I don't understand that response.")
else:
current = next
def read_course(fh):
# Reads the entire course from the data file handle fh.
questions = { }
finished = False
while not finished:
question = read_question(fh)
if question is None:
finished = True
else:
name = question.get_name()
if len(questions) == 0:
questions["START"] = question
questions[name] = question
return TMCourse(questions)
MARKER = "-----"
class TMQuestion:
def __init__(self, name, text, answers):
# New TMQuestion object with these attributes.
self._name = name
self._text = text
self._answers = answers
def get_name(self):
# Returns the name of this question.
return self._name
def get_text(self):
# Returns the list containing the text of this question.
return self._text
def lookup_answer(self, response):
# Looks up the response to find the next question.
next_question = self._answers.get(response, None)
if next_question is None:
next_question = self._answers.get("*", None)
return next_question
def read_question(fh):
# Reads one question from the data file handle fh.
name = fh.readline().rstrip()
if name == "":
return None
text = [ ]
finished = False
while not finished:
line = fh.readline().rstrip()
if line == MARKER:
finished = True
else:
text.append(line)
answers = { }
finished = False
while not finished:
line = fh.readline().rstrip()
if line == "":
finished = True
else:
colon = line.find(":")
if colon == -1:
raise ValueError("Missing colon in " + line)
response = line[:colon].strip().upper()
next_question = line[colon + 1:].strip()
answers[response] = next_question
return TMQuestion(name, text, answers)