I'd like to know how to make the following code shorter and/or more efficient. Could I (or should I) get rid of the for loop by using a functional method, or is there method I should be using from numpy?
The code calculates the expected value of an array of of integers.
vals = np.arange(self.n+1) # array of probability of each value in vals parr = np.ones(len(vals)) for i in range(len(vals)): parr[i] *= self.prob(vals[i]) return np.dot(vals,parr)
As requested in comments, the implementation of the method prob():
def prob(self, x): """Computes probability of removing x items :param x: number of items to remove :returns: probability of removing x items """ # p is the probability of removing an item # sl.choose computes n choose x return sl.choose(self.n, x) * (self.p**x) * \ (1-self.p)**(self.n-x)