Created
June 12, 2012 11:15
-
-
Save arnabkd/2916956 to your computer and use it in GitHub Desktop.
Example of FP and imperative in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment