vendredi 13 novembre 2020

Creating a class that choses random elements from list(s)

I'm currently working on a problem. In this problem I have to implement a Python class ProbRandom that is instantiated with two arguments, a finite data set and a probability list for that data set.

X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
P = [0.025 , 0.05, 0.075 , 0.125,  0.225,  0.225,  0.125 ,  0.075 , 0.05,  0.025]

class ProbRandom:
    def __init__ (self, dataset, problist):
        self.dataset = X
        self.problist = P

Then I have to add a method randomdata to the ProbRandom class. This method should take no arguments and return a random value from the data set. Use the Python module random to implement this method. The probability of what value is returned should be equal for all values in the data set.

def random_data():
    return random.choice(X)

Then. I have to add the method probrandomdata to the ProbRandom class. This method should take no arguments and return a random value from the data set. However, as opposed to the randomdata method, the probability of what random value from the data set is returned should match the corresponding probability in the probability list.

def prob_random_data():
    n = random.radint(0,10)
    return X[n], P[n]

Then I have to In create a program that uses the ProbRandom class to create two Python lists of integers, randomP and probRandomP. The length of the lists should be equal to the length of the data set(and the probability list). The items in the randomP list should count the number of times the value at the same position in the data set has been seen when calling the randomdata method. The items in the probRandomP list should count the number of times the value at the same position in the data set has been seen when calling the probrandomdata method. Call the two methods 1000 times each and count the number of occurrences of the values in the data set in each list.

#Here's the full code: 
import random
X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
P = [0.025 , 0.05, 0.075 , 0.125,  0.225,  0.225,  0.125 ,  0.075 , 0.05,  0.025]
class ProbRandom:
    def __init__ (self, dataset, problist):
        self.dataset = X
        self.problist = P
    print (len(X))
    print (len(P))
    
    def random_data():
        return random.choice(X)
    
    def prob_random_data():
        n = random.radint(0,10)
        return X[n], P[n]

Random = ProbRandom(X, P)
randomP = []
probRandomP = []
for i in range(1000):
    a = Random.random_data
    b = Random.prob_random_data
    randomP.append(a)
    probRandomP.append(b)
    
print (a)
print(b)

I don't get the desired output. What I get is:

<bound method ProbRandom.random_data of <main.ProbRandom object at 0x11d274c70>> <bound method ProbRandom.prob_random_data of <main.ProbRandom object at 0x11d274c70>>

When I should be getting two lists.




Aucun commentaire:

Enregistrer un commentaire