#!/usr/local/bin/python
import cgi
import string
import sys
sys.stderr = sys.stdout
form = cgi.FieldStorage()
# parse form data
print "Content-type: text/html\n\n" # plus blank
line
html = """
<TITLE>askmerlin.cgi</TITLE>
<H1>Merlin has carefully considered and weighed the
evidence, and he chooses</H1>
<HR>
<P> %s</P>
<HR>"""
from urllib import *
import re
import google
google.LICENSE_KEY =
"Wd23pfdQFHIHmc7G5eml/2dZEybvk5S3"
import string, sys
class Decision:
def get_list(self, heading, prompt):
print heading
print
print "(enter a blank line to end the list)"
ret = []
i = 1
while 1:
line = raw_input(prompt % i)
if not line:
break
ret.append(line)
i=i+1
print
return ret
def get_number(self, prompt):
res = None
while res is None:
try:
res = float(raw_input(prompt))
except ValueError: pass
return res
def getOptions(self):
self.options =
self.get_list("Enter your options", "Option %d: ")
def getCriteria(self):
self.criteria =
self.get_list("Enter your criteria ...", "Criterion %d: ")
def getWeights(self):
self.weights = {}
for c in
self.criteria:
print
print "Enter a relative importance factor, or weight, for each
criteria (higher is more important)"
print
self.weights[c] = self.get_number("Criterion %s: " % c)
def getScores(self):
self.scores = {}
for o in
self.options:
print
print "Scores for option %s" % o
print
for c in self.criteria:
self.scores[o,
c] = self.get_number("Criterion %s: " % c)
def getResults(self):
self.results = {}
for o in self.options:
value = 0
for c in self.criteria:
print o, c, self.weights[c], self.scores[o, c]
value = value + self.weights[c] * self.scores[o, c]
self.results[o] = value
self.results =
self.results.items() # A list of tuples (key,
value)
self.results.sort(lambda
x, y: -cmp(x[1], y[1]))
def printResults(self):
print
print "Results, in
order from highest to lowest score"
print
print "%5s %s"
% ("Score", "Option")
for option, result in
self.results:
print "%5s %s" % (result, option)
def turntheCrank(self):
self.getOptions()
self.getCriteria()
self.getWeights()
self.getScores()
self.getResults()
self.printResults()
class YesNo(Decision):
def turntheCrank(self):
self.options =
["Yes","No"]
self.getCriteria()
self.getWeights()
self.getScores()
self.getResults()
self.printResults()
class Lunch(Decision):
def turntheCrank(self):
print
print "This is a classified, top secret program developed by the
CIA. Please keep it confidential"
print
print "What should we do for lunch? ;-)))"
print
self.criteria
= ["taste", "convenience", "atmosphere",
"value"]
self.options = self.get_list("Enter your restaurants or other food
choices:", "Option %d: ")
self.getWeights()
self.getScores()
self.getResults()
self.printResults()
class Basketball(Decision):
def turntheCrank(self):
print "This is a
program to help you decide which team will win a basketball game"
print
print "When
prompted, enter a number ranking each team on the prompted team skill"
print "on a scale
from 1 to 100, with 1 being terrible and 100 being the best imaginable"
print
team_one = raw_input
("What is the name of team one: ")
team_two = raw_input
("What is the name of team two: ")
teams = (team_one,
team_two)
self.options = teams
self.weights =
{"speed":100, "size":66, "jumping_ability":50,
"defense":60, "shooting":75, "ballhandling":50, "rebounding":50}
self.criteria =
self.weights.keys()
self.getScores()
self.getResults()
self.printResults()
class Football(Decision):
def turntheCrank(self):
print "This is a
program to help you decide which team will win a football game"
print
print "When
prompted, enter a number ranking each team on the prompted team skill"
print "on a scale
from 1 to 100, with 1 being terrible and 100 being the best imaginable"
print
team_one = raw_input
("What is the name of team one: ")
team_two = raw_input
("What is the name of team two: ")
teams = (team_one,
team_two)
self.options = teams
self.weights =
{"speed and quickness":7, "size and strength":5,
"rushing offense":5, "passing offense":7,
"defense":1, "coaching":12}
self.criteria =
self.weights.keys()
self.getScores()
self.getResults()
self.printResults()
class Election(Decision):
def getOptions(self):
self.options = self.get_list("Enter
the name of each candidate", "Candidate %d: ")
def turntheCrank(self):
self.criteria =
["Education", "Social Issues", "Taxing and
Spending", "Character", "Intelligence",
"Leadership",
"Foreign Affairs"]
self.getOptions()
self.getWeights()
self.getScores()
self.getResults()
self.printResults()
class multiChoiceGuesser:
def __init__(self, question='', choices=()):
self.question = question
self.choices = choices
def guessedAnswer(self):
hits = []
result = []
results = {}
for choice in
self.choices:
x = (self._getGoogleHits(self.question + ' ' + choice))
y = (self._getGoogleHits(choice))
x = float(x)
y = float(y)
if y == 0:
y = y + 1
if x == 0:
x = x + 1
dividend = x / y
hits.append(dividend)
results[choice] = dividend
return
hits.index(max(hits))
def _getGoogleHits(self, query):
google.LICENSE_KEY =
"Wd23pfdQFHIHmc7G5eml/2dZEybvk5S3"
data =
google.doGoogleSearch(query)
hits =
data.meta.estimatedTotalResultsCount
return hits
def guess(self,question, choices):
self.mcg =
multiChoiceGuesser(question, choices)
xyz =
choices[self.mcg.guessedAnswer()]
return xyz
class AskMerlina(Decision, multiChoiceGuesser):
def turntheCrank(self):
self.question =
form['question'].value
self.choices =
form['choices'].value.split(",")
self.guess(self.question, self.choices)
class weightGuesser(Decision, multiChoiceGuesser):
google.LICENSE_KEY = "Wd23pfdQFHIHmc7G5eml/2dZEybvk5S3"
def __init__(self, question='', choices=(), criteria = (), num = {}, den
= {}, scores = {}):
self.question = question
self.choices = choices
self.criteria = criteria
self.num = num
self.den = den
self.scores = scores
def
guessedAnswer(self):
hits = []
result = []
results = {}
for choice in
self.choices:
for criterium in self.criteria:
x = (self._getGoogleHits(self.question + ' ' + choice + ' ' + criterium))
y = (self._getGoogleHits(choice))
x = float(x)
y = float(y)
print x, y
if y == 0:
y = y + 1
if x == 0:
x = x + 1
dividend = x / y
hits.append(dividend)
results[reply] = dividend
return
hits.index(max(hits))
def _getGoogleHits(self, query):
google.LICENSE_KEY =
"Wd23pfdQFHIHmc7G5eml/2dZEybvk5S3"
data =
google.doGoogleSearch(query)
hits =
data.meta.estimatedTotalResultsCount
return hits
def getScores(self):
import
google
google.LICENSE_KEY = "Wd23pfdQFHIHmc7G5eml/2dZEybvk5S3"
xyz = {}
self.scores = {}
for o in self.choices:
for c in self.criteria:
data = google.doGoogleSearch(o + ' ' + c + ' ' + self.question)
self.num[o, c] = data.meta.estimatedTotalResultsCount
float(self.num[o, c])
for o in self.choices:
for c in self.criteria:
data = google.doGoogleSearch(o)
self.den[o, c] = data.meta.estimatedTotalResultsCount
float(self.den[o, c])
xyz = self.den[o, c]/self.num[o, c]
self.scores[o, c] = xyz
def getResults(self):
self.results = {}
for o in self.choices:
value = 0
for c in self.criteria:
value = value + self.weights[c] * self.scores[o,c]
self.results[o] = 1.0/value
self.results =
self.results.items() # A list of tuples (key,
value)
self.results.sort(lambda
x, y: -cmp(x[1], y[1]))
def turntheCrank(self):
self.question =
raw_input ("What is your question? ")
self.choices =
self.get_list("Enter your options:", "Option %d: ")
self.criteria =
self.get_list("Enter your criteria:", "Option %d: ")
self.getWeights()
self.getScores()
self.getResults()
self.printResults()
decide = AskMerlina()
decide.turntheCrank()
print html % decide.guess(decide.question, decide.choices)