-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathzoo.py
78 lines (63 loc) · 1.9 KB
/
zoo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import numpy as np
import csv
import re
# Zoo class is a bot to simulate a human user against the 20Q bot.
# It supplies the 20Q bot with questions and responds to these questions
# from the dataset to ensure accuracy.
class Zoo(object):
def __init__(self,src):
self.questions = []
self.targets = []
self.qas = []
self.src = src
with open(self.src,'rb') as zoocsv:
entries = list(csv.reader(zoocsv))
labels = entries[0]
self.questions = labels[1:]
duplicates = 0
for row in entries[1:]:
tmp_qas = map(int,row[1:])
if tmp_qas not in self.qas: # remove indistinguishable entries
self.targets.append(row[0])
self.qas.append(map(int,row[1:]))
else:
duplicates+=1
print '\nloading',src,'...'
print len(self.targets),'targets','(',duplicates,'duplicates removed )'
print len(self.questions),'questions'
# get the answer from two strings
def get_answer(self,_question,_target):
for target in self.targets:
if target == _target:
for question in self.questions:
if question == _question:
return self.qas[self.targets.index(target)][self.questions.index(question)]
break
return None
# get the answer from a pair of question and target indexes
def get_answer_i(self,qi,ti):
ans = self.qas[ti][qi]
if ans == 1: return 1
else: return -1
def animal_in_list(self,_target):
if _target in self.targets:
return True
return False
# test the zoo bot to verify its reliability
def test(self):
target = raw_input('Enter animal: ')
while (self.animal_in_list(target) == False):
print 'Animal not in list. Please pick another animal...'
target = raw_input('Enter animal: ')
while True:
question = raw_input('Question: ')
answer = self.get_answer(question,target)
if answer == 1:
print 'Yes'
elif answer == 0:
print 'No'
else:
print 'Unknown question'
if __name__ == "__main__":
z = Zoo('big.csv')
z.test()