-
Notifications
You must be signed in to change notification settings - Fork 0
/
OneDigitArith.py
executable file
·115 lines (93 loc) · 2.78 KB
/
OneDigitArith.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python3
import random
import time
import sys
def getInt(str):
"""Try and try again to get integer."""
while True:
try:
return int(input(str))
except:
pass
def buildIndexArray(distrib):
"""convert dictionary, like {'x':1, 'y':2, 'z':3} to ['x','y','y','z','z','z']
The purpose is to control the chance of the element. For the array above,
if we pick random element, 1/6 chance for 'x', 2/6 chance for 'y', and 3/6
chance for 'z'."""
indexArr = []
for k, v in distrib.items():
indexArr.extend([k] * v)
return indexArr
def getRandomNumber():
"""get random number, from 0-10 with custom chance distribution."""
# The keys on the dict below is the number and the value is how likely that
# number will be selected.
distrib = {
0: 1,
1: 1,
2: 1,
3: 1,
4: 1,
5: 1,
6: 1,
7: 3,
8: 4,
9: 3,
10: 1,
}
indexArr = buildIndexArray(distrib)
return indexArr[random.randint(0, len(indexArr) - 1)]
def getProblem():
"""Construct an arithmetic problem. Return (problem-string, answer)."""
def add():
a = getRandomNumber()
b = getRandomNumber()
return ('{} + {} = '.format(a, b), a + b)
def mult():
a = getRandomNumber()
b = getRandomNumber()
return ('{} x {} = '.format(a, b), a * b)
def minus():
a = getRandomNumber()
b = getRandomNumber()
big = max(a, b)
small = min(a, b)
return ('{} - {} = '.format(big, small), big - small)
def divide():
a = getRandomNumber()
b = 0
while b == 0:
b = getRandomNumber()
return ('{} / {} = '.format(a * b, b), a)
distrib = {
add: 1,
mult: 2,
divide: 2,
minus: 1,
}
indexArr = buildIndexArray(distrib)
return indexArr[random.randint(0, len(indexArr) - 1)]()
def main():
"""Start the arithmetics!!"""
random.seed()
total = getInt('total number of questions: ')
correct = 0
wrong = 0
start = time.time()
for i in range(0, total):
(problem, correctAnswer) = getProblem()
answer = getInt(problem)
if answer == correctAnswer:
correct += 1
else:
wrong += 1
print ('wrong. the right answer: %d' % (correctAnswer))
end = time.time()
print ('total correct: %d (%.1f%%)' % (correct, correct / total * 100))
print ('total wrong: %d (%.1f%%)' % (wrong, wrong / total * 100))
deltaSecs = end - start
print ('total time: %d minutes %d seconds' % (int(deltaSecs / 60), deltaSecs % 60))
input('press <Enter> to quit program...')
return 0
if __name__ == '__main__':
sys.exit(main())