use random functions (python)
I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas like this:
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = choice([process,process1,process2])
test(data)
run()
main()
Can we choice one random function to process the data ? If yes, is this a good way to do so ?
Thanks 开发者_JAVA百科!
Excellent approach (net of some oversimplification in your skeleton code). Since you ask for an example:
import random
def main():
def process(data):
return data + [0]
def process1(data):
return data + [9]
def process2(data):
return data + [7]
def run(data):
test = random.choice([process,process1,process2])
print test(data)
for i in range(7):
run([1, 2, 3])
main()
I've made it loop 7 times just to show that each choice is indeed random, i.e., a typical output might be something like:
[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 0]
[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 9]
[1, 2, 3, 9]
(changing randomly each and every time, of course;-).
Sure is!
That the nice thing in Python, functions are first class objects and can be referenced in such an easy fashion.
The implication is that all three methods have the same expectation with regards to arguments passed to them. (This probably goes without saying).
Just use the random number module in python.
random.choice(seq)
This will give you a random item from the sequence.
http://docs.python.org/library/random.html
Your code will work just like you wrote it, if you add this to the top:
from random import choice
Or, I think it would be slightly better to rewrite your code like so:
import random
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = random.choice([process,process1,process2])
test(data)
run()
main()
Seeing random.choice()
in your code makes it quite clear what is going on!
精彩评论