Probability is how likely an event will occur. It is the value of how likely an event is to occur divided by the total outcomes. For example, the probability of drawing an ace out of a deck of cards, choosing a number out of a set of numbers where the number is prime, tossing a coin, selecting a colored ball out of a bag, etc. These are all different probability problems.
To write a program for a probability question, there are two basic steps:
First, collect a set of items/events.
Then, write a function to solve the problem.
Let’s take the example of choosing one number out of a set of numbers. We can find different probabilities for this particular problem; for instance:
and so on.
We will first take the set of numbers the user is going to perform the probability algorithm on.
set_of_numbers=[]n=int(input("enter the number of elements: "))print("enter the elements: ")for i in range(0,n):j=int(input())set_of_numbers.append(j)#print the set of numbersprint(" the set of numbers are: ",set_of_numbers)
Now let’s solve all the problems one by one.
Let’s say the first probability question is to choose an even number. The first function would be to find the number of even numbers out of the given set of numbers.
def probability_of_even(a):c = 0total = len(a)for i in a:if i % 2 == 0:c += 1return c / totalset_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]print("The probability of choosing an even number would be:", probability_of_even(set_of_numbers))
The second probability question might be to choose a prime number. We will write a function to calculate the number of prime numbers that are present in that particular set and return the probability value.
def probability_of_prime(a):c = 0total = len(a)for i in a:if i > 1:c2 = 0for j in range(2, i):if i % j == 0:c2 += 1if c2 == 0:c += 1return c / totalset_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]print("The probability of choosing a prime number would be:", probability_of_prime(set_of_numbers))
Let’s say the last probability question is choosing a number that is divisible by both 3 and 5. Then, the function would be as follows:
def probability_divisible(a):c = 0total = len(a)for i in a:if i % 3 == 0 and i % 5 == 0:c += 1return c / totalset_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]print("The probability of choosing a number divisible by 3 and 5 is:", probability_divisible(set_of_numbers))
For any given probability problem, we can follow the same procedure, i.e., take the set of events/items first, and then write functions to solve the probability question.