Skip to content

Instantly share code, notes, and snippets.

@faried
Created July 5, 2015 14:45
Show Gist options
  • Save faried/6049890be7d2901691fd to your computer and use it in GitHub Desktop.
Save faried/6049890be7d2901691fd to your computer and use it in GitHub Desktop.
simple word problems in python
#!/usr/bin/env python
"""Simple word questions.
pip install python-slugify gTTS inflect
"""
from random import choice, randint, randrange
import os
import os.path
from time import sleep
from gtts import gTTS
from inflect import engine
from slugify import slugify
SOUNDTMPL = "/tmp/wp/%s.mp3"
SCORE = "\n\n\t\t\tRight: %(correct)s Wrong: %(incorrect)s"
PHRASES = {"right": "yay!", "wrong": "wrong answer!"}
TEMPLATE = """
%(name1)s has %(count1)s %(thing1)s. \
%(name2)s gives %(name1)s %(count2)s %(thing2)s.
"""
QUESTION = "How many %(thing2)s does %(name1)s have? "
# range for random numbers: MIN to MAX inclusive
MIN = 1
MAX = 5
PEOPLE = ["Musa", "Bilal", "Zelif", "Hassan", "Uzair", "Raza"]
THING = ["ball", "book", "box", "car", "cat", "pencil", "pen", "magazine",
"computer", "monitor", "keyboard", "mouse", "laptop", "sharpener"]
def say(text, speak=True):
"""Play mp3 file, downloading and caching if necessary."""
slug = slugify(text)
fname = SOUNDTMPL % slug
if not os.path.exists(fname):
tts = gTTS(text=text, lang="en")
tts.save(fname)
if speak:
os.system("mpg123 -q %s" % fname)
def setup():
"""Sounds, etc."""
if not os.path.exists("/tmp/wp"):
os.mkdir("/tmp/wp")
# cache correct/incorrect responses
for phrase in PHRASES.values():
say(phrase, False)
return engine()
def wrong():
print(PHRASES["wrong"])
say(PHRASES["wrong"])
def right():
print(PHRASES["right"])
say(PHRASES["right"])
def play(p):
correct = 0
incorrect = 0
score = 0
name1 = choice(PEOPLE)
name2 = choice(PEOPLE)
while name2 == name1:
name2 = choice(PEOPLE)
thing = THING[randrange(0, len(THING))]
count1 = randint(MIN, MAX)
count2 = randint(MIN, MAX)
wanted = count1 + count2
thing1 = p.plural(thing, count1)
thing2 = p.plural(thing, count2)
# in words
count1 = p.number_to_words(count1)
count2 = p.number_to_words(count2)
tpl = TEMPLATE % locals()
print(tpl)
say(tpl)
while True:
ask = QUESTION % locals()
say(ask)
answer = raw_input(ask)
if answer.strip():
try:
answer = int(answer, 10)
except ValueError:
print("wrong answer!")
say(PHRASES["wrong"])
else:
if answer != wanted:
wrong()
incorrect += 1
else:
right()
correct += 1
break
return (correct, incorrect)
def main():
"""Main branching logic."""
correct = incorrect = 0
p = setup()
while True:
try:
(correct, incorrect) = play(p)
except KeyboardInterrupt:
print(SCORE % locals())
break
if __name__ == '__main__':
main()
# eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment