Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

python - Dictionary Calling Function for Each Key

I have the following code in which I am trying to build a random number object based on the type of distribution and the parameters of said distribution. The code works insomuch as it generates an object that contains 10,000 points from a uniform distribution.

import numpy as np

rngSeed = 654  # Random seed for reproducibility
numSimulations = 10_000


def get_rand_unif(min_value, max_value, n_samples=1_000):
    """
    This function generates a random number [nd]array of size [n_samples]
    from a uniform distribution between the two input values
    [min_value, max_value)
    Args:
    - min_value (float)
    - max_value (float)
    - n_samples (int)
    Return:
    - Random number [nd]array of [n_samples] between this range (float)
    """
    return np.random.default_rng(rngSeed).uniform(min_value, max_value, n_samples)


def get_rand_norm(mean, std_dev, n_samples=1_000):
    """
    This function generates a random number [nd]array of size [n_samples]
    from a normal distribution with a mean of [mean] and a standard deviation
    of [std_dev].
    Args:
    - mean(float)
    - std_dev (float)
    - n_samples (int)
    Return:
    - Random number [nd]array of [n_samples] from a normal distribution (float)
    """
    return np.random.default_rng(rngSeed).normal(mean, std_dev, n_samples)


class InVar:
    def __init__(self, *parms):
        self.rndData = self.get_disto(*parms)

    def get_disto(self, *parms):
        distR = {
            "unif": get_rand_unif(parms[1], parms[2], numSimulations),
            "norm": get_rand_norm(parms[1], parms[2], numSimulations),
        }
        return distR.get(parms[0])

    def rand_data(self):
        return self.rndData

p1 = InVar("unif", 0, 1)

However, when I debug the code, I notice that random values are being calculated for both the Uniform and Normal distributions. I would like to know how to change my code so that only the function corresponding to the called key is executed. While anecdotal, I fear that if I were to introduce additional probability distributions that require more than two parameters, I will run into trouble.

Debug Output

question from:https://stackoverflow.com/questions/66048854/dictionary-calling-function-for-each-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the simple fix you're looking for is to call the function after the dict is constructed.

def get_disto(self, *parms):
    distR = {
        "unif": get_rand_unif,
        "norm": get_rand_norm,
    }
    return distR.get(parms[0])(parms[1], parms[2], numSimulations)

UPDATE: If you want to call the functions separately, like you did before, use an if/else construct.

def get_disto(self, *parms):
    if parms[0] == "unif":
        return get_rand_unif(parms[1], parms[2], numSimulations)
    elif parms[0] == "norm":
        return get_rand_norm(parms[1], parms[2], numSimulations)
    else:
        raise Exception(f"Unrecognized distribution type: {parms[0]}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...