Home > Back-end >  Python Regenerate Random Numbers if Condition is not met
Python Regenerate Random Numbers if Condition is not met

Time:09-07

I want to evaluate an expression and regenerate the random numbers in __init__ method of Class if the condition is met. Code for that is below

import random

class RandomNumbers:
    def __init__(self):
        self.BASE_A = random.randint(2, 10)
        self.BASE_B = random.randint(2, 10)

        self.EXPONENT_N = random.randint(2, 7)
        self.EXPONENT_P = random.randint(2, 7)

        # Ensure result 
        while self.BASE_A ** self.EXPONENT_N - \
                self.BASE_B ** self.EXPONENT_P == 0:
            # re initiate BASE_A, BASE_B, EXPONENT_N, EXPONENT_P
            pass

    def generate(self):
        return self.BASE_A, self.EXPONENT_N, self.BASE_B, \
               self.EXPONENT_P

How can I call __init__ within __init__ if self.BASE_A ** self.EXPONENT_N - self.BASE_B ** self.EXPONENT_P == 0 ?

CodePudding user response:

You would want to do something like this. assign all of the values in a seperate method and if they are incorrect call that same method again.

import random

class RandomNumbers:
    def __init__(self):
        self.assign_values()
        while (self.BASE_A ** self.EXPONENT_N - 
               self.BASE_B ** self.EXPONENT_P == 0):
            self.assign_valuse()

    def assign_values(self):
        self.BASE_A = random.randint(2, 10)
        self.BASE_B = random.randint(2, 10)
        self.EXPONENT_N = random.randint(2, 7)
        self.EXPONENT_P = random.randint(2, 7)


    def generate(self):
        return self.BASE_A, self.EXPONENT_N, self.BASE_B, \
               self.EXPONENT_P
  • Related