Quizbank/Python/numerical/numericalFunctions.py
< Quizbank | Python/numerical
The main reason I created this file to hold functions is that the code that creates each question needs to be simple and user friendly for those who don't know Python very well. In our original attempt used a Java code that read script and converted it into Java code that performed the calculations required to write all the (random-number) renditions of a given question. Then MATLAB was used because students on our campus know it. But the pedagogical nature of Python makes it ideal[1] for this purpose.
##These functions and a class write numerical questions one at
##a time. Place the template.py file one level above and modify
##both the contents and title of this template. The template names
##identify the name of the question. This will create a text
##file with all the renditions. The textfile's name also follows
##the name of the question. Place all the questions into a new
##folder named after the name of the quiz and run the program
##inside that folder. It will assemble all the questions into
##a page of wikitext that can be uploaded to Wikiversity.
#Give me flexibility in question sig fig
sigFigQues=2
### converts to string
strSigFig=str(sigFigQues)
import os, csv, re, time, shutil, random, sys, math
random.seed()
def roundSigFig(x, sigFig): #rounds x to significant figures
from math import log10, floor
return round(x, sigFig-int(floor(log10(abs(x))))-1)
class QuesVar:
def __init__(self, first, low, high, firstQuestion):
self.precision=2 #Number of digits to round
self.first=first
# see if either low or high are floating
oneFloats=isinstance(low,float) or isinstance(high,float)
if firstQuestion:
temp=first #temp is the local variable for self.v
self.v=temp #v=value
else: #it is not the first question and may or may not float
if oneFloats: #select a random floating value
temp=random.uniform(low,high)
temp=roundSigFig(temp,sigFigQues)
self.v=temp
else:
temp=random.randint(low,high)
temp=roundSigFig(temp,sigFigQues)
self.v=temp
#tempV=self.v and is used to create self.t (text version
if temp > .01 and temp < 1000:
self.t=str(temp)
else:
formatStatement='{0:1.'+strSigFig+'E}'
#self.t='{0:1.3E}'.format(temp)
self.t=formatStatement.format(temp)
def express(x):
if x > .01 and x < 1000:
result=str(x)
else:
result='{0:1.2E}'.format(x)
return result
def makeAnswers(pre, rightAns, post, fact):
alphabet = "abcdefghijklmnopqrstuvwxyz"
answerKeys=['-','-' ,'-','-','-']#add the + later
answers=[] #define list
nCor=random.randint(0,4) #randomly select correct answer
answerKeys[nCor]='+'
answerString=''
for n in range(5):
temp=answerKeys[n]+alphabet[n]+') '
temp=temp + pre +"{:.3E}".format(rightAns*fact**(n-nCor))
temp = temp + post + '\n'
answerString=answerString+temp
return(answerString)
## end diagnostic printout
Footnote edit
- ↑ Shouldn't "ideal" be spelled IDLE in this context (Python joke).