# L-13 MCS 275 Wed 10 Feb 2010 : treezoo.py def Add(d): """ Adds a new element to the dictionary, via interactive questions to the user. """ if len(d) == 0: a = raw_input('What animal ? ') return [a] elif len(d) == 1: q = 'Is it \"' + d[0] + '\" ? (y/n) ' a = raw_input(q) if a == 'y': print 'okay, got it' return d else: a = raw_input('What animal ? ') s = 'Give question to distinguish \"' + \ a + '\" from \"' + d[0] + '\":\n' q = raw_input(s) return {'q':q,'y':[a],'n':[d[0]]} else: a = raw_input(d['q'] + ' (y/n) ') if a == 'y': return {'q':d['q'],'y':Add(d['y']),'n':d['n']} else: return {'q':d['q'],'y':d['y'],'n':Add(d['n'])} def Navigate(d): """ Navigates through the dictionary based on the user responses. """ if len(d) == 1: print 'arrived at \"' + d[0] + '\"' elif len(d) == 3: a = raw_input(d['q'] + ' (y/n) ') Navigate(d[a]) def main(): """ Build interactively a tree to classify animals. """ d = {} while True: d = Add(d) print 'd =', d a = raw_input("continue ? (y/n) ") if a != 'y': break print 'ended construction, start navigation...' while True: Navigate(d) a = raw_input("continue ? (y/n) ") if a != 'y': break main()