Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

How to skip multiple times call a function in class?

I designed a class named Funcskip. I want to randomly call function which are defined into the class. But I also want to skip functions which are called already. How can I do this from following code.

import random
class Funcskip:
    def __init__(self,
                 min_ops=2,
                 max_ops=4):
      self.min_ops                =   min_ops
      self.max_ops                =   max_ops
      self.ops              =   [self.__add, self.__sub, self.__mult, self.__div]

    def __initParams(self):
      self.num_ops          =    random.randint(self.min_ops,self.max_ops)

    def __add(self, a, b):
      print("1. add")
      return a+b
    def __sub(self, a,b):
      print("2. sub")
      return a-b

    def __mult(self, a, b):
      print("3. mult")
      return a*b
    def __div(self, a,b):
      print("4. div")
      return a//b

    def callF(self,a,b):
        self.__initParams()
        print(self.num_ops)
        total = 0
        for _ in range(self.num_ops):
            total+=random.choice(self.ops)(a,b)
        return total

    

  
obj = Funcskip()
a = 10
b = 5
_total = obj.callF(a,b)
print(_total)
                 

Upvotes: 1

Views: 226

Answers (3)

U13-Forward
U13-Forward

Reputation: 71610

Remove it from the list:

def callF(self,a,b):
    self.__initParams()
    print(self.num_ops)
    for _ in range(self.num_ops):
        func = random.choice(self.ops)
        total = func(a,b)
    self.ops.remove(func)
    return total

Upvotes: 0

quamrana
quamrana

Reputation: 39404

Just shuffle the list and call the first few functions:

    def callF(self,a,b):
        self.__initParams()
        ops = self.ops[:]
        random.shuffle(ops)
        print(self.num_ops)
        total = 0
        for op in ops[:self.num_ops]:
            total += op(a, b)
        return total

Upvotes: 2

I'mahdi
I'mahdi

Reputation: 24059

random.choice from range(len(list)) then use .pop(idx).

Try this:

def callF(self,a,b):
    self.__initParams()
    print(self.num_ops)
    total = 0
    for _ in range(self.num_ops):
        idx = random.choice(range(len(self.ops)))
        total += self.ops.pop(idx)(a,b)
    return total

Upvotes: 1

Related Questions