Skip to content

Instantly share code, notes, and snippets.

@kvalle
Last active December 14, 2015 08:49
Show Gist options
  • Save kvalle/5060523 to your computer and use it in GitHub Desktop.
Save kvalle/5060523 to your computer and use it in GitHub Desktop.
import re
from flask import Flask, request
app = Flask(__name__)
@app.route('/', endpoint='index')
def index():
question = request.args.get("q", "").partition(": ")[2]
answer = solve(question)
print "\nQ: %s?\nA: %s" % (question, answer)
return answer
solvers = {
"what is your name": lambda m: "tkk",
"what is the twitter id of the organizer of this dojo": lambda m: "@olemartin",
"who played James Bond in the film Dr No": lambda m: "Sean Connery",
"which city is the Eiffel tower in": lambda m: "Paris",
"who is the Prime Minister of Great Britain": lambda m: "David Cameron",
"what is ([\d]+) plus ([\d]*)":
lambda m: int(m.group(1)) + int(m.group(2)),
"what is ([\d]+) multiplied by ([\d]*)":
lambda m: int(m.group(1)) * int(m.group(2)),
"what is ([\d]*) minus ([\d]*)":
lambda m: int(m.group(1)) - int(m.group(2)),
"which of the following numbers is the largest:(.*)":
lambda m: str(max([int(t) for t in m.group(1).split(", ")])),
"what is ([\d]*) to the power of ([\d]*)":
lambda m: int(m.group(1))**int(m.group(2)),
"which of the following numbers are primes:(.*)":
lambda m: first_prime([int(t) for t in m.group(1).split(", ")]),
"what is the ([\d]*)th number in the Fibonacci sequence":
lambda m: fib(int(m.group(1))),
"what is (.+)": lambda m: solve_math(m)
}
def solve(q):
for pattern, fn in solvers.iteritems():
m = re.match(pattern, q)
if m:
answer = fn(m)
if answer: return str(answer)
return "???"
def solve_math(m):
try:
exp = m.group(1) \
.replace("plus", "+") \
.replace("minus", "-") \
.replace("multiplied by", "*")
return eval(exp)
except Exception:
return None
def isprime(n):
n = abs(int(n))
if n < 2: return False
if n == 2: return True
if not n & 1: return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def first_prime(tall):
for t in tall:
if isprime(t):
return t
def memoize(fn):
cache = {}
def wrapper(arg):
if arg in cache:
return cache[arg]
else:
cache[arg] = fn(arg)
return cache[arg]
return wrapper
@memoize
def fib(a):
if a in (0,1): return a
return fib(a-1) + fib(a-2)
if __name__ == "__main__":
app.run(debug=True, port=1337, host="localhost")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment