public
Created

Example of FP and imperative in python

  • Download Gist
math_quiz.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#Task 9.5 - Arnab Kumar Datta (arnabkd)
import operator,random
levels = {'B' : 10 , 'I': 25 , 'A':100}
func = {'add': operator.add, 'mul' : operator.mul, 'sub' : operator.sub}
ops = {func['add'] : '+' , func['mul'] : '*', func['sub'] : '-'}
messages = ['Please ask your math teacher for help!','You need more practice.',\
'Well done!']
 
def play(level,op):
operand1 = random.randint(1,level); operand2 = random.randint(1,level)
ans = op(operand1, operand2)
input = int(raw_input(('Enter your answer for %d %s %d : ')\
%(operand1, ops[op],operand2 )))
return 1 if input == ans else 0
 
def feedback(points,rounds):
ratio = float(points) / float(rounds)
if (ratio > (2.0/3.0)): #more than 2/3rd correct
print messages[2]
elif(ratio >= (1.0/3.0)): #more than, or exactly 1/3rd correct
print messages[1]
else: #less than 1/3rd correct
print messages[0]
 
def main():
level = levels[raw_input("Choose difficulty (B)eginner / (I)ntermediate"+\
" / (A)dvanced: ")]
rounds = int (raw_input("Enter how many rounds you would like to play: "))
type = (raw_input("What type of quiz do you want :\nmul/sub/add/mix : "))
 
points = 0
if 'mix' not in type:
for i in range (rounds) : points += play(level,func[type])
else :
for i in range (rounds) : points += play(level, random.choice(func.values()))
 
feedback(points,rounds)
 
if (raw_input("Type \'r\' and press enter to restart the quiz\n")) == 'r' :
main()
 
if __name__ == "__main__":
main()
 
"""
Runtime example
 
arnabkd@stcroix ~/Desktop/uni/inf3331/inf3331/ukesoppgaver/uke9 $ python math_quiz.py
Choose difficulty (B)eginner / (I)ntermediate / (A)dvanced: B
Enter how many rounds you would like to play: 3
What type of quiz do you want :
mul/sub/add/mix : mix
Enter your answer for 10 - 5 : 5
Enter your answer for 6 + 1 : 7
Enter your answer for 9 - 1 : 0
You need more practice.
Type 'r' and press enter to restart the quiz
 
"""

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.