#! /usr/bin/env python """ Creates random questions for PacMath @license: U{http://creativecommons.org/licenses/by-sa/3.0/us/} """ from random import randint import pygame class questionGenerator: """ A reusable object which is used to generate questions @var operation: The operation that the math questions will incorporate @var minOp: The minimum allowable value for an operand @var maxOp: The maximum allowable value for an operand """ def __init__(self, operation, minOp, maxOp): """ Constructor @var operation: The operation that the math questions will incorporate @var minOp: The minimum allowable value for an operand @var maxOp: The maximum allowable value for an operand """ self.minOp = minOp self.maxOp = maxOp self.operation = operation def getQuestion(self): """ Returns a single question based on the constraints the generator was created with @return A tuple contining two strings: ("question", "answer") """ op1 = randint(self.minOp, self.maxOp) op2 = randint(self.minOp, self.maxOp) if( self.operation == ['x'] ): answer = op1*op2 return (str(op1)+" x " + str(op2) + " = ?", str(answer)) if( self.operation == ['+'] ): answer = op1+op2 return (str(op1)+" + "+ str(op2) + " = ?", str(answer)) elif( self.operation == ['-'] ): answer = op1-op2 return (str(op1)+" - "+ str(op2) + " = ?", str(answer)) elif( self.operation == ['/'] ): answer = op1*op2 return (str(answer)+" / "+ str(op1) + " = ?", str(op2)) else: return null def getQuestionSet(self): """ Returns a set of four questions for use in a round of pacmath, ensures that no questions have duplicate answers. Fails and exits if four questions with distinct answers cannot be generated from this constraint set (eg minOp = 2, maxOp = 3: only 2 * 2, 2 * 3, 3 * 3) @return A list with four questions in the form ("question", "answer") """ questions = [] attempts = 0 while len(questions) < 4 and attempts < 100: toAdd = self.getQuestion() notDuplicate = True for i in questions: if toAdd[1] == i[1]: notDuplicate = False attempts += 1 if notDuplicate: questions.append( toAdd ) if attempts >= 100: print "Bad question set, not enough questions could be generated" print "Minimum Operand: " + str(self.maxOp) print "Maximum Operand: " + str(self.minOp) print "Operation: " + str(self.operation) raise SystemExit return questions