Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Run a Random Function in Python 2

Suppose I have two functions:

functionA() and functionB()

I do not care which function runs, but I do want just ONE of them to run randomly--ie, if I run the script a hundred times, both should be played near 50 times.

How can I program that into Python 2?

like image 525
Matt Avatar asked Oct 18 '22 09:10

Matt


1 Answers

In Python, functions are first class citizens so you can put them in a list and then randomly select one of them at every turn using random.choice:

>>> import random

>>> functions = [functionA, functionB]
>>> for _ in range(100):
...     function = random.choice(functions)
...     function()
like image 106
Ozgur Vatansever Avatar answered Nov 01 '22 10:11

Ozgur Vatansever