Passioire
Passioire

Reputation: 19

How do I run several functions in a random order for x amount of times?

I'm creating a quiz with 10 questions and I want the following functions to run 10 times. This is my current solution, but it only runs each function once. Each function is a different question.

def sumchoice():
    sums = [add(), sub(), multiply()]
    for _ in range(10):
        sums

What I want it to do is run the functions in a random order but only ten times altogether. I've thought of using a while loop, but that doesn't seem to work.

Upvotes: 0

Views: 786

Answers (3)

kvivek
kvivek

Reputation: 3491

There is an inbuild module called operator and random, which can be used, The operator module can be used for the binary operations and random can be used for getting the random choice and the random number. And there is an inbuilt function called apply, which can also be used.

>>> help(apply)


Help on built-in function apply in module __builtin__:

apply(...)
    apply(object[, args[, kwargs]]) -> value

    Call a callable object with positional arguments taken from the tuple args,
    and keyword arguments taken from the optional dictionary kwargs.
    Note that classes are callable, as are instances with a __call__() method.

    Deprecated since release 2.3. Instead, use the extended call syntax:
        function(*args, **keywords).

This is an alternate approach.

from operator import add, sub, mul, div
import random

binaryOps = (add, sub, mul, div )
#nums = ( int(raw_input('Enter number 1: ')), int(raw_input('Enter number 2: ')))
nums = (random.randint(0, 1000), random.randint(0, 1000))

def method_choice(nums):
    op = random.choice(binaryOps)
    return nums[0], nums[1], apply(op, nums)

for iteration in range(10):
    print method_choice(nums)

Upvotes: 0

Selcuk
Selcuk

Reputation: 59425

You are pre-calling all the functions while creating the list. You should remove the parantheses () from the list and call them inside the for loop:

import random

def add():
    print "add"

def sub():
    print "sub"

def multiply():
    print "multiply"

sums = [add, sub, multiply]
for _ in range(10):
    random.choice(sums)()

Result:

multiply
add
multiply
sub
sub
multiply
multiply
sub
sub
sub

Upvotes: 0

Th30n
Th30n

Reputation: 303

Instead of calling functions you store them in a list.

import random

def sumchoice():
    sums = [add, sub, multiply]
    for _ in range(10):
        fun = random.choice(sums) # This picks one function from sums list
        fun() # This calls the picked function

Upvotes: 1

Related Questions