[ rss / options / help ]
post ]
[ b / iq / g / zoo ] [ e / news / lab ] [ v / nom / pol / eco / emo / 101 / shed ]
[ art / A / beat / boo / com / fat / job / lit / map / mph / poof / £$€¥ / spo / uhu / uni / x / y ] [ * | sfw | o ]
logo
technology

Return ]

Posting mode: Reply
Reply ]
Subject   (reply to 27217)
Message
File  []
close
Fritz Honka.jpg
272172721727217
>> No. 27217 Anonymous
21st August 2019
Wednesday 12:35 pm
27217 https://pastebin.com/2X1w76RJ
Ihave made a mental arithmetic brain trainer.

It generates expressions at random like "6 * 3" that you have to evaluate as fast as possible.

It's set to use numbers 1-10 but you can gradually increase the range as you get better.

I recommend training for 20 mins a day.
Expand all images.
>> No. 27218 Anonymous
21st August 2019
Wednesday 1:33 pm
27218 spacer
Mental gymnastics trainer when?
One could scrape all the cunt-off threads for examples.
>> No. 27219 Anonymous
21st August 2019
Wednesday 4:10 pm
27219 spacer
>>27217
I mean, cool. But what for? There are plenty of more advanced trainers available and this is such a simple program that anyone with the wherewithal to know how to run this could have surely written the same thing?

Plus, you say "as fast as possible", but the program doesn't keep a score or even time you.
>> No. 27220 Anonymous
21st August 2019
Wednesday 4:26 pm
27220 spacer
>>27219
Plus, I'm not au fait with Python best practice so this may not be as big of an issue in this case, but raising an exception when the program is running normally is usually not advised. If you're not interested in timing or scorekeeping, you could really have condensed all this down to:


--------
while not done:
a = random.randint(1, 10)
b = random.randint(1, 10)
op = random.choice(['+', '-', '*'])

exp = '%d %s %d' % (a, op, b)
answer = eval(exp)

print('\n' + exp + '\n')

guess = input().strip().upper()

if guess == 'Q':
done = True;
else:
print('\nWRONG. Answer is %d' % answer) if int(guess) != answer else print ('Correct!')

--------

This will also let the user keyboard interrupt the program with ctrl+c.
>> No. 27221 Anonymous
21st August 2019
Wednesday 4:38 pm
27221 spacer
>>27220

Someone enters "ASS", program crashes.

I suppose answer could be cast to string to avoid this.
>> No. 27223 Anonymous
21st August 2019
Wednesday 4:45 pm
27223 spacer
>>27221

import random while True: a = random.randint(1, 10) b = random.randint(1, 10) op = random.choice(['+', '-', '*']) exp = '%d %s %d' % (a, op, b) answer = str(eval(exp)) print('\n' + exp + '\n') if input().strip() != answer: print('\nWRONG. Answer is %s.' % answer)

>> No. 27224 Anonymous
21st August 2019
Wednesday 5:33 pm
27224 spacer
Here's a version I've thrown together that measures your reaction time.

It's probably not best practice, but I don't usually Python.

import random import time print('''Enter 'q' to quit''') done = False questions = 0 while(questions == 0): print('Enter a number of questions to answer:\n') try: questions = int(input().strip()) except: print('Please enter a valid value.\n') questionNo = 1 reactTimes = [] correctAnswers = 0 while ((not done) and questionNo <= questions): a = random.randint(1, 10) b = random.randint(1, 10) op = random.choice(['+', '-', '*']) exp = '%d %s %d' % (a, op, b) answer = eval(exp) print('\n' + exp + '\n') startTime = time.time() UserIn = input().strip().upper() if UserIn == 'Q': done = True; else: if UserIn != str(answer): print('\nWRONG. Answer is %d' % answer) else: endTime = time.time() elapsedTime = (endTime-startTime)*1000 reactTimes.append(elapsedTime) correctAnswers = correctAnswers + 1 print ('Correct! %d milliseconds.\n' % elapsedTime) questionNo = questionNo + 1 if(not done): avgReact = sum(reactTimes)/len(reactTimes) print('You got', correctAnswers, 'out of', questions, 'correct, with an average correct answer reaction time of', avgReact, 'milliseconds.')

>> No. 27226 Anonymous
21st August 2019
Wednesday 10:02 pm
27226 spacer
>>27224
> It's probably not best practice, but I don't usually Python.

I assume you normally do C-style languages? If I may:

1) 4 space indent, not tabs. Python being bondage & discipline about indentation does have an established standard here that is less optional than in other languages.

2) eval is frowned upon, in this instance using the "operator" module would be the "pythonic" choice.

3) Drop the semicolon. I know it's second nature if you do C-like code a lot, but not needed and considered noise.

4) Wrap in a main function and do the 'if name == "__main__"' dance. For a throwaway it barely matters, but if if you ever do write even slightly serious python you'll love not having code execcuted on import.

5) No brackets around the if/while conditional statements, just space.

6) Triple ''' are usually reserved for multi-line or doc strings, ' can live in ". This one's a bit more matter of taste, though.

7) "%" formatting is on the way out, ".format" is winning. I like "%" formatting, but them's them beans.

8) You never set done to True when the questions run out, so it won't print a result. You may want to ditch the "done" variable entirely and just "break" on "Q", then check for zero-length on the arrays to avoid crashing when printing the stats.
>> No. 27227 Anonymous
21st August 2019
Wednesday 10:40 pm
27227 spacer
>>27226
You picked up all those complaints and yet missed the Lego strings?
>> No. 27228 Anonymous
21st August 2019
Wednesday 10:56 pm
27228 spacer
>>27226
I'm not OP, but yes. I primarily C++.

I modified the OP's code, and probably would have attacked a lot of the stuff a different way (the done and eval I found clunky but trying to extend OP's code so it's a decent starting point for learning. That, and laziness.).
>> No. 27229 Anonymous
21st August 2019
Wednesday 11:01 pm
27229 spacer
>>27226
Also, regarding point 8 -- I'm not sure what you mean. the while loop will terminate once the given number of questions is exceeded, or "done" becomes true, whichever comes first.

If the while loop exited due to done becoming true, then the if statement will not run, and the program will terminate. The if statement (and hence the results) will ONLY print if done is false.
>> No. 27230 Anonymous
22nd August 2019
Thursday 12:38 am
27230 spacer
>>27226
How's this?

ess = input().strip() != answer:\n')
a = random.randint(1, 10)
b = random.randint(1, 10)
a = random.choice(['+', '-', '*'])

exp = '%d %s %d' % (a, op, b)
answers, 'correct answer = eval(exp))

if int(guess) != answer = eval(exp)

print('\nWRONG. Answer:
b = randint(1, 10)
print('\n' + exp + '\n')

guess) != answer)
import random.randint(1, 10)
op = random.choice(['+', '-', '*'])
a = random.choice(['+', '-', '*'])

print('Enter a number of questionNo = 1
reactTime)*1000
reactTime = True;
else:
print('\n' + exp + '\n')

guess == 'Q':
done = True:

op = random.randint(1, 10)
op = '%d %s %d' % (a, op, b)
print('\nWRONG. Answer = str(eval(exp)

print ('CorrectAnswers = int(1, 10)
exp = '%d %s %d' % answers = 0


print('\nWRONG. Answers + 1
print('You got', correctAnswer is %d' % answer react, 'milliseconds.\n' + exp + '\n' + exp + '\n')

done = True;
else:
endTime = time.time()
else print('\n' % elapsedTime = time.time()
UserIn == 'Q':
done = True;
else:
print ('Correct! %d milliseconds.')
edTime = (endTime = True:
print ('Correct!')
try:
done = True;
else:
if UserIn != str(answer) if int(guess) != answer)
done = False

while(questions, 'correct!')
import random.random.randint(1, 10)
except:
print('\n' + exp + '\n')

guess == 'Q':
done = True;
else:
elapsedTime = time.time()
print('Please enter a number of questionNo = 1
reactTimes)/len(reactTimes)
print('\n' + exp + '\n')

questions to answer = eval(exp)

while(questionNo = 1
reactTimes.append(elapsedTime)

questions = 0

while not done) and questionNo = question time.time()
reactTimes)/len(reactTimes)
print('Please enter a number of questionNo = 1
reaction time()

if(not done:
a = random.choice(['+', '-', '*'])
print ('Correct!')
try:
print('\n')

except:
print(1, 10)
op = random.randint(1, 10)

exp = '%d %s %d' % (a, op, b)
answer)
elapsedTime = time.time()
UserIn != answer = eval(exp)

print('''Enter 'q' to quit''')

answer is %s.' % answers, 'correctAnswers, 'out of', avgReact, 'milliseconds.\n' % answer = eval(exp)

print ('Correct answers = correctAnswer is %d' % answer):
reactTimes = []
correctAnswers = 0

guess) != answer is %s.' % answer = str(answer react, 'milliseconds.\n' + exp + '\n' + exp + '\n')

avgReact, 'milliseconds.')
rint
>> No. 27231 Anonymous
22nd August 2019
Thursday 12:47 am
27231 spacer

Ward Cunningham.jpg
272312723127231
I'm on to you OP.
>> No. 27232 Anonymous
22nd August 2019
Thursday 1:00 am
27232 spacer
>>27230
Code tags, man.
>> No. 27233 Anonymous
22nd August 2019
Thursday 10:45 am
27233 OP
This is my final code.

import random, re lo = 1 hi = 10 nQuestions = 250 print('''Using numbers in range {}-{}. {} questions. Press ctrl+c to exit early. ---------------'''.format(lo, hi, nQuestions)) for i in range(nQuestions): if i > 0 and i % 25 == 0: print('\n---{} questions remaining---'.format(nQuestions - i)) a = random.randint(lo, hi) b = random.randint(lo, hi) op = random.choice([[(lambda x,y: x+y), '+'], [(lambda x,y: x-y), '-'], [(lambda x,y: x*y), '*']]) answer = op[0](a, b) print('\n{} {} {} =\n'.format(a, op[1], b)) userIn = input().strip() if not re.match(r'[+-]?\d+', userIn) or int(userIn) != answer: print('\nWRONG. Answer is {}.'.format(answer))

>> No. 27234 Anonymous
22nd August 2019
Thursday 12:25 pm
27234 spacer
>>27233

i'm going to do 250 questions a day and increase 'hi' by 1 every week.
>> No. 27235 Anonymous
22nd August 2019
Thursday 5:12 pm
27235 spacer
>>27233
Needs something to increase the stakes. Such as, say, encrypting random files if you get the answer wrong.
>> No. 27237 Anonymous
22nd August 2019
Thursday 6:42 pm
27237 spacer
Would it be overkill to make an Operator class like this:

class Operator: def __init__(self, fn, symbol): self.fn = fn self.symbol = symbol

>> No. 27246 Anonymous
26th August 2019
Monday 12:59 pm
27246 spacer
>>27233

Regex should be anchored like this:

^[+-]?\d+$

>> No. 27249 Anonymous
28th August 2019
Wednesday 4:40 pm
27249 spacer
import random, re #Custom classes ############################################ class Operator: def __init__(self, fn, symbol): self.fn = fn self.symbol = symbol #Functions ############################################ def getHi(): try: with open('hi.txt', 'r') as file: return int(file.readline().strip()) except: return 10 def incrementHi(): with open('hi.txt', 'w') as file: file.write(str(hi + 1)) #Constants ############################################ lo = 1 hi = getHi() nQuestions = 250 passingMark = 98 #integer percent add = Operator((lambda x,y: x+y), '+') sub = Operator((lambda x,y: x-y), '-') mul = Operator((lambda x,y: x*y), '*') #Start ############################################# print('''Using numbers in range {}-{}. {} questions. Passing mark is {}%. Press ctrl+c to exit early. ---------------'''.format(lo, hi, nQuestions, passingMark)) nCorrect = 0 for i in range(nQuestions): if i == nQuestions - 1: print('\n---Last question---') elif i > 0 and (nQuestions - i) % 25 == 0: remaining = nQuestions - i s = '' if remaining == 1 else 's' print('\n---{} question{} remaining---'.format(remaining, s)) a = random.randint(lo, hi) b = random.randint(lo, hi) op = random.choice([add, sub, mul]) answer = op.fn(a, b) print('\n{} {} {} =\n'.format(a, op.symbol, b)) userIn = input().strip() if re.match(r'^[+-]?\d+$', userIn) and int(userIn) == answer: nCorrect += 1 else: print('\nWRONG. Answer is {}.'.format(answer)) score = (100.0 * nCorrect) / nQuestions print(''' --------------- Score: {0:.2f}%'''.format(score)) if score >= passingMark: print('\nLesson passed. Number range will be increased by 1 next lesson.\n') incrementHi() else: print('\nLesson failed. Lesson will be repeated.\n') print('Press enter to exit.') input()

>> No. 27250 Anonymous
28th August 2019
Wednesday 7:16 pm
27250 spacer
>>27249

Add this operator:

pow = Operator(lambda x,y: x***y, '^')

>> No. 27253 Anonymous
1st September 2019
Sunday 6:00 pm
27253 OP
I've developed this a bit more. I've added division, square and cube questions and refactored the code a bit.

import math, random, re #Custom classes ############################################ class Question: def __init__(self, equation, answer): self.equation = equation self.answer = answer #Functions ############################################ def getHi(path): try: with open(path, 'r') as file: return int(file.readline().strip()) except: print('''---Error: Unable to access "{}" and load 'hi' value.--- ---Using default value of 10.---\n'''.format(path)) return 10 def incrementHi(path, newHi): try: with open(path, 'w') as file: file.write(str(newHi)) except: print('---Error: Unable to access "{}" and increase number range.---\n'.format(path)) def findBiFactorisations(n): factors = [] for i in range(2, n + 1): for j in range(2, n + 1): if i * j == n: factors.append((i, j)) return factors def isComposite(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return True return False def findNonPrimes(lo, hi): nonPrimes = [] for i in range(lo, hi + 1): if isComposite(i): nonPrimes.append(i) return nonPrimes def makeAddQuestion(): a = random.randint(lo, hi) b = random.randint(lo, hi) return Question('{} + {} ='.format(a, b), int(a + b)) def makeSubQuestion(): a = random.randint(lo, hi) b = random.randint(lo, a) return Question('{} - {} ='.format(a, b), int(a - b)) def makeTimesQuestion(): a = random.randint(lo, hi) b = random.randint(lo, hi) return Question('{} * {} ='.format(a, b), int(a * b)) def makeDivQuestion(): a = random.choice(nonPrimes) b, answer = random.choice(findBiFactorisations(a)) return Question('{} / {} ='.format(a, b), int(a / b)) def makeSquareQuestion(): a = random.randrange(lo, hi) return Question('{} ^ 2 ='.format(a), int(a ** 2)) def makeCubeQuestion(): a = random.randrange(lo, hi) return Question('{} ^ 3 ='.format(a), int(a ** 3)) #Constants ############################################ hiFile = r'hi.txt' lo = 1 hi = getHi(hiFile) # must be at least 4 nonPrimes = findNonPrimes(lo, hi) nQuestions = 250 passingMark = 98 # integer percent questionMakers = [makeAddQuestion, makeSubQuestion, makeTimesQuestion, makeDivQuestion, makeSquareQuestion, makeCubeQuestion] #Start ############################################# print('''Using numbers in range {}-{}. {} questions. Passing mark is {}%. Press ctrl+c to exit early. ---------------'''.format(lo, hi, nQuestions, passingMark)) nCorrect = 0 for i in range(nQuestions): if i == nQuestions - 1: print('\n---Last question---') elif i > 0 and (nQuestions - i) % 25 == 0: print('\n---{} questions remaining---'.format(nQuestions - i)) question = random.choice(questionMakers)() print('\n{}\n'.format(question.equation)) userIn = input().strip() if re.match(r'^[+-]?\d+$', userIn) and int(userIn) == question.answer: nCorrect += 1 else: print('\nWRONG. Answer is {}.'.format(question.answer)) score = round(100 * nCorrect / nQuestions, 2) if score % 1 == 0: score = int(score) print(''' --------------- Score: {}%'''.format(score)) if score >= passingMark: print('\nLesson passed. Number range will be increased by 1 next lesson.\n') incrementHi(hiFile, hi + 1) else: print('\nLesson failed. Lesson will be repeated.\n') print('Press enter to exit.') input()

Return ]
whiteline

Delete Post []
Password