import sys import bisect class AZ: filename = "nessybot-words" def __init__(self): self.words = [] fd=open(self.filename,"r") for word in fd: self.words.append(word) fd.close() self.words.sort() self.new() def guess(self, bound=1): """Perform the binary guess If the number of words is less than *bound* then display all the words within the range. Otherwise, pick the binary search of the remaining words. Note that the returned guess may not be valid, so it may be necessary to fudge things a bit""" self._guess = self._lower + (self._upper - self._lower)/2 print "debug: lower ", self.words[self._lower], \ "upper ", self.words[self._upper] print "guess: ", self.words[ self._guess ] avail = self._upper - self._lower if avail <= bound : for i in range(self._lower, self._upper+1): print self.words[i], def lbound(self, val): """Update the bounds in response to a clue""" print "debug: ", val, bisect.bisect(self.words, val) self._lower = bisect.bisect(self.words, val) def ubound(self, val): """Update the bounds in response to a clue""" self._upper = bisect.bisect(self.words, val) + 1 def hint(self, tokens): """Parse out provided hint and update bounds""" self.lbound(tokens[9]) self.ubound(tokens[11]) self.guess(10) def new(self): self.save() self._lower = 0 self._upper = len(self.words)-1 self._guess = self._lower + (self._upper - self._lower)/2 print "debug: new game" def save(self): f = open(self.filename, "w") for word in self.words: f.write(word) f.close() print "debug: saved" def reject(self): self.words.remove( self.words[self._guess] ) self._upper -= 1 self.guess(10) def add(self, word): new_word = word + '\n' self.words.append(word) self.words.sort() self.save() print "debug: added (and saved)" def play(self): """Play the game""" while ( True ): line = sys.stdin.readline() tokens = line.split() if len(tokens) < 1 : continue if len(tokens) > 10 : self.hint(tokens) if tokens[0] == "reject" : self.reject() if tokens[0] == "hint" : self.hint(tokens) if tokens[0] == "quit" : return if tokens[0] == "new" : self.new() if tokens[0] == "save" : self.save() if tokens[0] == "add" : self.add(tokens[1]) if __name__ == '__main__': a = AZ() a.play()