Luca Tatas
Luca Tatas

Reputation: 190

Executing functions randomly in python according to number of times every function should be executed

I have a class containing multiple methods which will be called multiple times in a random matter. I want to achieve the following:

I want the user to input the number of times every function should be called.

Right now I have the following implementation, which works perfectly fine but for me it does not seem to be very "elegant":

import random

class MyClass:
    def __init__(self, a_count, b_count):

        a = list("A")*a_count
        b = list("B")*b_count
        self.action_list = a+b

    def a(self):
        print("A called!")

    def b(self):
        print("B called!")

    def execute(self):
        action_count = range(len(self.action_list))

        for i in action_count:
            elem = random.choice(self.action_list)
            if elem == "A":
                self.a()
            if elem == "B":
                self.b()
            self.action_list.remove(elem)        

myClass = MyClass(4,2)
myClass.execute()

So in this example it runs a() 4 times and b() 2 times, but this happens randomly, so for example the output could be looking something like this:

A called!
B called!
A called!
A called!
A called!
B called!

All in all, I don't think that's the best way of getting the desired behaviour. I mean this implementation works, but it doesn't really satisfy my desire of writing "good" code.

Maybe someone has a better idea.

Thanks in advance!

Upvotes: 0

Views: 45

Answers (2)

Belhadjer Samir
Belhadjer Samir

Reputation: 1669

you can try this :

import random

class MyClass:
    def __init__(self, a_count, b_count):
        self.func = [self.a for e in range(a_count)]+[self.b for e in range(b_count)]
    def a(self):
        print("A called!")

    def b(self):
        print("B called!")

    def execute(self):
      print(self.func)
      for e in range(len(self.func)):
          func = random.choice(self.func)
          func()
          self.func.remove(func)
myClass = MyClass(4,2)
myClass.execute()

Upvotes: 0

Aziz Sonawalla
Aziz Sonawalla

Reputation: 2502

Here's a more concise version:

class MyClass:

    def __init__(self, a_count, b_count):
        self.action_list = [self.a]*a_count + [self.b]*b_count  # a list of method references rather than strings
        random.shuffle(self.action_list)   # shuffle the list once randomly

    def a(self):
        print("A called!")

    def b(self):
        print("B called!")

    def execute(self):
        [elem() for elem in self.action_list]  # call every method in the list

Upvotes: 3

Related Questions