lundi 16 avril 2018

How do I randomly call one of three functions without using an if statement?

I created a class "Bruch" that creates two fractions from random numbers in a given range. There are three different types of operations that are defined in three different functions, for addition (bruchplus), subtraction(bruchminus) and multiplication (bruchmulti).

The "select(self)" function randomly calls one of these.

The code works totally fine, but I am not happy with the "if" clause in select(self). It's clumsy and ugly. There must be a more pythonic way to accomplish this. (I tried to call the functions from within a list, but that will call all the three functions, even if i just return e.g. list[0]). Looking forward to your input!

class Bruch:
    def __init__(self, name):
        self.name = 'BRUCHRECHNEN'
        print(self.name)
        print('')
        self.a = Fraction(rdm.randrange(1,10,2),rdm.randrange(2,10,2))
        self.b = Fraction(rdm.randrange(1,10,2),rdm.randrange(2,10,2))   

    #randomly selects + / - / x and calls the respective function      
    def select(self):
        number = rdm.randint(0,2)
        if number == 0:
            p = self.bruchplus()
        elif number == 1:
            p = self.bruchminus()
        else:
            p = self.bruchmulti()
        return p




Aucun commentaire:

Enregistrer un commentaire