Python Regenerate Random Numbers if Condition is not met

Viewed 36

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 ?

2 Answers

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

You don't need a separate method just to assign values like @Alexander's answer does.

Instead, put the assignments in a while loop, and break the loop only if the desired condition is met:

class RandomNumbers:
    def __init__(self):
        while True:
            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)
            if self.BASE_A ** self.EXPONENT_N - self.BASE_B ** self.EXPONENT_P != 0:
                break
Related