-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharithmanic.py
132 lines (102 loc) · 3.6 KB
/
arithmanic.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import math
import json
import random
from operator import add, mul, sub, truediv
from collections import namedtuple
savefile = os.path.expanduser('~/.mentalmath.dat')
Result = namedtuple('Result', 'ok op left right value'.split())
operators = {'+': add, '-': sub, 'x': mul, '/': truediv}
def load(filename):
with open(filename, 'r') as f:
dicts = map(json.loads, f)
record = list(Result(**d) for d in dicts)
return record
def save(record, filename):
with open(filename, 'a') as f:
for r in record:
dat = json.dumps(r._asdict())
f.write('{}\n'.format(dat))
def choose_operands(left_range, right_range, shuffle=False):
left = random.randint(*left_range)
right = random.randint(*right_range)
if shuffle and random.random() > 0.5:
left, right = right, left
return (left, right)
def make_q_and_a(op, left, right, digits=1):
q = "{:{digits}} {} {:{digits}}".format(left, op, right, digits=digits)
if op == '/' and right == 0:
a = float('inf')
else:
a = operators[op](left, right)
return q, a
def read(prompt):
try:
return raw_input(prompt)
except NameError:
return input(prompt)
def eq(resp, a):
trunc = lambda n: math.floor(10000.0 * float(n)) / 10000.0
return trunc(resp) == trunc(a)
def make_challenge(op, range1, range2, shuffle):
left, right = choose_operands(range1, range2, shuffle=shuffle)
digits = max(map(len, map(str, range1 + range2)))
q, a = make_q_and_a(op, left, right, digits=digits)
def challenge():
resp = read("{} = ".format(q))
try:
ok = eq(resp, a)
except ValueError:
ok = False
return Result(ok=ok, op=op, left=left, right=right, value=a)
return challenge
def show_stats(record):
import pprint
pprint.pprint(record)
def main():
"""Run main."""
import argparse
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('--range', '-r', type=int, metavar='INT',
default=[0, 12], nargs=2,
help='Lowest and highest operand values')
parser.add_argument('--range2', '-r2', type=int, metavar='INT', nargs=2,
help='Lowest and highest other operand values')
parser.add_argument('--ops', '-o', metavar='OPERATION',
help='Arithmetic op (+-x/)')
parser.add_argument('--shuffle', '-s', action="store_true")
args = parser.parse_args()
# db = load()
if args.ops:
assert set(args.ops) <= set(operators)
candidate_ops = list(args.ops)
else:
candidate_ops = list(operators.keys())
try:
record = []
range1 = args.range
range2 = args.range2 if args.range2 else args.range
while True:
op = random.choice(candidate_ops)
# weights = db[op]
challenge = make_challenge(op, range1, range2, args.shuffle)
tries = 2
while tries:
result = challenge()
if not result.ok:
print("!!! NO NO NO NO NO !!!")
record.append(result)
tries = 0 if result.ok else tries - 1
if not result.ok:
print(" {}".format(result.value))
# weight(weights, left, right, result.ok)
except (EOFError, KeyboardInterrupt):
print()
show_stats(record)
save(record, savefile)
return 0
if __name__ == '__main__':
main()