Use random functions (python)

I wonder if we can do this in python, suppose we have 3 different functions for processing data for example:

def main():
  def process(data):
     .....
  def process1(data):
     .....
  def process2(data):
     .....
  def run():
     test = choice([process,process1,process2])
     test(data)
  run()

main()

Is it possible to choose one random function for data processing? If so, is this a good way to do this?

Thanks!

+3
source share
4 answers

Great approach (due to some simplification in your skeleton code). Since you are requesting 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 did this 7 times to show that each choice is really random, i.e. a typical output might look something like this:

[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 time, of course, -).

+4
source

Of course!!

Python, .

, . (, , ).

+3

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

+1
source

Your code will work the same way you wrote it if you add this at the top:

from random import choice

Or, I think it would be a little better to rewrite your code like this:

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, he clearly explains what is happening!

0
source

Source: https://habr.com/ru/post/1723134/


All Articles