Generating random math operators

This is the place for queries that don't fit in any of the other categories.

Generating random math operators

Postby stargirl » Sat Feb 09, 2013 2:34 am

I could use some major help...

How can I random generate operators in python?

For example if I wanted to randomly generate math probs like:

6 + 6

9 * 2

12 / 4

10 - 2

I know how to generate the random numbers for the equation but I can't for the life of me figure out how to randomly generate the operators (* / + -)How can I do this? This is driving me insane. Please help!
stargirl
 
Posts: 5
Joined: Sat Feb 09, 2013 2:31 am

Re: Generating random math operaors

Postby stranac » Sat Feb 09, 2013 12:16 pm

Hope you don't mind my moving your post.
The topic you posted in is just a joke between a few of the regular members, and your problem doesn't really belong there.


How to do this depends on what you actually want to do.
If you just want to generate strings for display, this should do:
Code: Select all
>>> import random
>>> random.choice('+-*/')
'/'

If you wish to do something more than that, you'll need to give us a bit more details before we can provide any real assistance.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1127
Joined: Thu Feb 07, 2013 3:42 pm

Re: Generating random math operaors

Postby Mekire » Sat Feb 09, 2013 12:22 pm

This depends... are you simply interested in creating strings? I.e. just printing out random questions. If so this can be done easily:
Code: Select all
from random import choice,randint

def rand_math():
    a,b = randint(0,10),randint(0,10)
    rand_op = choice(["+","-","/","*"])
    print("{0} {1} {2}".format(a,rand_op,b))

if __name__ == "__main__":
    for x in range(20):
        rand_math()



Edit: Gah... beaten to the punch yet again... good ol' times.
User avatar
Mekire
 
Posts: 987
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Generating random math operaors

Postby Yoriz » Sat Feb 09, 2013 1:15 pm

If its not just printing a string that you want, to get the actual calculation done with random maths operator you could do as shown in the following code.
The first is just the maths the second is return the full equation as a string.

Code: Select all
from operator import add, sub, mul, div
from random import randint, choice


def random_math(x, y):
    '''Randomly chooses a math operator to do on 2 values given'''
    func = choice((add, sub, mul, div))
    return func(x, y)

try:
    print random_math(randint(0, 10), randint(0, 10))
except ZeroDivisionError as exception:
    print exception


def random_math_string(x, y):
    '''Randomly chooses a math operator to do on 2 values given
    returns a string representing the full equation'''
    index = randint(0, 3)
    op = [add, sub, mul, div]
    symbols = '+-*/'
    return '{} {} {} = {}'.format(x, symbols[index], y, op[index](x, y))


try:
    print random_math_string(randint(0, 10), randint(0, 10))
except ZeroDivisionError as exception:
    print exception
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 784
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Generating random math operaors

Postby metulburr » Sat Feb 09, 2013 1:36 pm

i guess ill still add my two cents even though this has been beaten to a pulp

Code: Select all
import random

#definition
ops = ['*','/','-','+','**']
def num():
   return random.randint(1,100)

#assignment
left = num()
right = num()
op = random.choice(ops)

#calculation
if op == '*':
   ans = left * right
elif op == '-':
   ans = left - right
elif op == '+':
   ans = left + right
elif op == '/':
   ans = left / right
elif op == '**':
   ans = left ** right

#response
print('{} {} {}'.format(left, op, right))
print(ans)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1423
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Generating random math operaors

Postby ichabod801 » Sat Feb 09, 2013 2:20 pm

What? No eval?

Code: Select all
from __future__ import print_function
import random

def random_math(x, y, operators = [' + ', ' - ', ' * ', ' / ', ' ** ', ' % ']):
   operator = random.choice(operators)
   # avoid that division by zero operator
   while y == 0 and operator.strip() in '//%':
      operator = random.choice(operators)
   math_str = str(x) + operator + str(y)
   result = eval(math_str)
   print(math_str, ' = ', str(result))
   return result

if __name__ == '__main__':
   result = random_math(8, random_math(0, 1))
Craig "Ichabod" O'Brien
Minimalist, buddhist, theist, and programmer
Current languages: Python, SAS, and C++
Previous serious languages: R, Java, VBA, Lisp, HyperTalk, BASIC
ichabod801
 
Posts: 84
Joined: Sat Feb 09, 2013 12:54 pm
Location: Outside Washington DC

Re: Generating random math operaors

Postby stranac » Sat Feb 09, 2013 2:27 pm

ichabod801 wrote:What? No eval?

eval() is evil.
We don't want new users to deal with black magic.
Even experienced users should avoid it.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1127
Joined: Thu Feb 07, 2013 3:42 pm

Re: Generating random math operaors

Postby ichabod801 » Sat Feb 09, 2013 2:53 pm

stranac wrote:eval() is evil.
We don't want new users to deal with black magic.
Even experienced users should avoid it.


Ah, yes. Anti-eval paranoia. The boards are definitely back up. :lol:
Craig "Ichabod" O'Brien
Minimalist, buddhist, theist, and programmer
Current languages: Python, SAS, and C++
Previous serious languages: R, Java, VBA, Lisp, HyperTalk, BASIC
ichabod801
 
Posts: 84
Joined: Sat Feb 09, 2013 12:54 pm
Location: Outside Washington DC

Re: Generating random math operaors

Postby KevinD » Sat Feb 09, 2013 4:16 pm

ichabod801 wrote:Ah, yes. Anti-eval paranoia. The boards are definitely back up. :lol:


You'll know the old board is back when we start preaching against the goto module :lol:

It's good to be back.
Quanto lignum posset materiae materietur marmota Chuck si materiam possit materiari foedans, penitus lignum?
KevinD
 
Posts: 30
Joined: Fri Feb 08, 2013 3:15 am

Re: Generating random math operaors

Postby stargirl » Sat Feb 09, 2013 7:34 pm

Wow! Thanks for all the help...I ended up getting it to work (at least it appears to work) before my post was approved...lol
Btw, I am learning to program in Python 3.3.0 and the code that most of you guys put up appears to be either way too advanced for me at this point or a different version of Python(?)

I need to get this to loop so that if the user enters the wrong answer it keeps asking them to try again indefintely...well at least until they get it right...

For some reason it is not working correctly...i believe it is because of my assignments of the equations ex. mult = (num1 * num2)...

Why won't this work? Can anyone help?

Here is the original code that worked:


Code: Select all
def main():

    import random
    random.seed()

    num1 = random.randint(1, 5)
    num2 = random.randint(6, 10)
   
    mult = (num1 * num2)
    div = (num1 / num2)
    add = (num1 + num2)
    sub = (num1 - num2)

    correct = mult, div, add, sub
   
    opMULT = ("-")
    opDIV = ("+")
    opADD = ("*")
    opSUB = ("/")

    operators = opMULT, opDIV, opADD, opSUB

    op = random.choice(operators)
   
    print("\nWelcome! Here is your practice problem:\n")

    print(num1 ,op, num2)

    user_answer = float(input("\nAnswer: "))

    if user_answer == mult:
        print("\nYup!\n")

    elif user_answer == div:
        print("\nYup!\n")

    elif user_answer == add:
        print("\nYup!\n")

    elif user_answer == sub:
        print("\nYup!\n")

    else:
        print("\nNope")
       
         
main()



And here is the code with the loop that doesn't work now:


Code: Select all
def main():

    import random
    random.seed()

    num1 = random.randint(1, 5)
    num2 = random.randint(6, 10)
   
    mult = (num1 * num2)
    div = (num1 / num2)
    add = (num1 + num2)
    sub = (num1 - num2)

    correct = mult, div, add, sub
   
    opMULT = ("-")
    opDIV = ("+")
    opADD = ("*")
    opSUB = ("/")

    operators = opMULT, opDIV, opADD, opSUB

    op = random.choice(operators)

    print("\nWelcome! Here is your practice problem:\n")

    print(num1 ,op, num2)

    user_answer = float(input("\nAnswer: "))


    while user_answer != correct:
        print("Try again friend!")
        user_answer = float(input("\nAnswer: "))

    else:
        print("You finally got it genius!")
   
       
main()


Edited by stranac: changed the b tags to code
stargirl
 
Posts: 5
Joined: Sat Feb 09, 2013 2:31 am

Re: Generating random math operaors

Postby bunburya » Sat Feb 09, 2013 7:39 pm

Glad you got it sorted stargirl. Just so you know, you should generally wrap your code in CODE tags like so:
Code: Select all
[code]your code here[/code]


This will preserve the format of your code, especially the indentation. Unless we can see the indentation we can't know how your code is supposed to work.
http://www.bunburya.eu | https://github.com/bunburya

Join the #python-forum IRC channel on irc.freenode.net!
bunburya
 
Posts: 9
Joined: Sat Feb 09, 2013 7:28 pm
Location: Dublin, Ireland

Re: Generating random math operaors

Postby stargirl » Sat Feb 09, 2013 7:50 pm

Thanks for the quick reply :)

I will use CODE next time thanks :)

Ok, I also have another question...

I am finding that when the equation is division ex. (num1 / num2) if the answer is a long decimal i think i have to type EVERY digit in order for the answer to be correct...

I would like to shorten that down to two decimal places but i don't know where to put the "%.2f"...any help with this?
stargirl
 
Posts: 5
Joined: Sat Feb 09, 2013 2:31 am

Re: Generating random math operaors

Postby metulburr » Sat Feb 09, 2013 7:55 pm

Code: Select all
>>> floater = 10.123456789
>>> s = '{:.2f}'.format(floater)
>>> s
'10.12'
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1423
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Generating random math operaors

Postby stargirl » Sat Feb 09, 2013 8:18 pm

What version of python is that written in?

I don't recognize "s = '{:.2f}'.format(floater)"
stargirl
 
Posts: 5
Joined: Sat Feb 09, 2013 2:31 am

Re: Generating random math operaors

Postby stranac » Sat Feb 09, 2013 8:22 pm

correct is a tuple of 4 elements, (mult, div, add, sub).

The user's input will never be equal to that.
This is the reason you never leave the while loop.

You need to make sure correct only contains the actual correct answer.
Both Yoriz and metulburr showed ways how to do that, or you can try coming up with your own.

stargirl wrote:Btw, I am learning to program in Python 3.3.0 and the code that most of you guys put up appears to be either way too advanced for me at this point or a different version of Python(?)

Most people still use python 2.x, since it's still the better supported version, but the differences aren't huge.
The code posted is not very advanced, but it's understandable if you, as a beginner, don't understand all of it.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1127
Joined: Thu Feb 07, 2013 3:42 pm

Re: Generating random math operaors

Postby stargirl » Sat Feb 09, 2013 8:27 pm

I don't know where to start to "make sure correct only contains the actual correct answer."

Example please?

Once again, thanks for all of your help :)
stargirl
 
Posts: 5
Joined: Sat Feb 09, 2013 2:31 am

Re: Generating random math operaors

Postby metulburr » Sat Feb 09, 2013 8:29 pm

What version of python is that written in?

I don't recognize "s = '{:.2f}'.format(floater)"


It is written in python3.x, but is same for python 2.7 ( at least)
It is the string format method. where the value of floater is inserted into the string by
Code: Select all
{}
, and
Code: Select all
:.2f
formats it 2 decimal places. The idea was to do the calculation as float, and output the formatted answer in string
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1423
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Generating random math operaors

Postby stranac » Sat Feb 09, 2013 8:38 pm

stargirl wrote:I don't know where to start to "make sure correct only contains the actual correct answer."

Example please?

Once again, thanks for all of your help :)

One approach is to first figure out which operator was used, and then calculate the correct answer.
metulburr's first post has pretty simple code that does just that.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1127
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: Vurek and 3 guests