basic arithmetic, API & questions organization, ID generation

This commit is contained in:
Xevion
2020-08-27 01:31:52 -05:00
parent 3e052d3692
commit 1596518757
4 changed files with 109 additions and 0 deletions

31
server/api.py Normal file
View File

@@ -0,0 +1,31 @@
from flask import current_app, jsonify, request
from server import questions
from server.helpers import generate_id
# Stores active questions in memory for checking answers.
# Keys represent random question IDs. Values are Question objects.
active_questions = {}
categories = {
'arithmetic': questions.get_arithmetic
}
@current_app.route('/api/<category>/new')
def new_question(category: str):
q_id = None
while q_id in active_questions.keys() or q_id is None:
q_id = generate_id(5)
active_questions[q_id] = categories[category]()()
return jsonify(active_questions[q_id])
@current_app.route('/api/<category>/check')
def check_question(category: str):
if 'id' not in request.args.keys():
return jsonify({'error': ''}), 400
return jsonify({'answer': active_questions.get(request.args[id])})

66
server/arithmetic.py Normal file
View File

@@ -0,0 +1,66 @@
"""
arithmetic.py
Organizes all questions related to basic arithmetic, i.e. the four primary mathematical operations.
Also includes arithmetic related to exponents (positive and negative), fractions and more.
"""
import inspect
import random
def addition():
a, b = random.randint(6, 70), random.randint(6, 70)
return {
'type': inspect.stack()[0][3],
'question': f'{a} + {b}',
'answer': a + b
}
def subtraction():
a, b = random.randint(6, 70), random.randint(6, 70)
return {
'type': inspect.stack()[0][3],
'question': f'{a} - {b}',
'answer': a - b
}
def multiplication():
a = random.randint(2, 18)
b = random.randint(2, 26 - a)
return {
'type': inspect.stack()[0][3],
'question': f'{a} x {b}',
'answer': a * b
}
def division():
a = random.randint(2, 18)
b = random.randint(2, 26 - a)
return {
'type': inspect.stack()[0][3],
'question': f'{a * b} ÷ {b}',
'answer': a
}
def simplify_fraction():
a = random.randint(1, 12)
b = random.randint(2, 20 - a)
# Multiply by even/odd to
c, d = a, b
while c + d <= 15:
multiplier = random.randint(2, 3)
c, d = c * multiplier, d * multiplier
return {
'type': inspect.stack()[0][3],
'question': f'Simplify. \\frac{{{c}}}{{{d}}}',
'answer': f'{c}/{d}'
}
questions = [addition, subtraction, multiplication, division, simplify_fraction]

6
server/helpers.py Normal file
View File

@@ -0,0 +1,6 @@
import random
import string
def generate_id(length: int):
return ''.join(random.choices(string.ascii_letters, k=length))

6
server/questions.py Normal file
View File

@@ -0,0 +1,6 @@
import random
from server import arithmetic
def get_arithmetic():
return random.choice(arithmetic.questions)