Search code examples
pythonfunctionclassprobability-distribution

How can I use a probability distribution in python class?


Say I have the following class:

class Vehicle:

    def __init__(self, pevtype):
        self.pevtype = pevtype

How can I write a function which uses a probability distribution to determine whether the vehicle is an EV or a PHEV?

For example, the function setVehicle() would enable:

>>> v1.pevtype = 'EV'
>>> v2.pevtype = 'PHEV'

Solution

  • You could use numpy.random.choice. It takes a list of items that you want to chose from, and you can pass it the probability associated with each item as well. In the following example, I stored the information in a dict, where the keys are the items you want to chose from, and the values are the respective probabilities:

    import numpy as np
    
    
    class Vehicle:
        def __init__(self, pevtypes):
            self.pevtype = np.random.choice(
                list(pevtypes), p=list(pevtypes.values())
            )
    
    car_types = {'EV': 0.3, 'PHEV': 0.7}
    
    # for a single car
    car = Vehicle(car_types)
    
    print(car.pevtype)
    
    # for 2 or more cars e.g. like this
    cars = [Vehicle(car_types) for _ in range(3)]