Python program to find probability of getting letter 'a' in some letters and k sized combinations



Suppose we have an array with n different English letters. We also have another value k. We can select k different indices (1-indexed) with uniform distribution. We have to find the probability that at least one of the k indices selected will contain the letter 'a'.

So, if the input is like letters = ['a', 'c', 'a', 'b', 'l', 'a', 'b', 'z'] k = 2, then the output will be 64.28%. There are combinations like (1, 2), (1, 3) like there are 28 combinations but some of them like (1,2), (1,3), (6,7) such 18 pairs are holding 7, so 18/28 = 0.6428.

To solve this, we will follow these steps −

  • contain := 0
  • total := 0
  • for each combination c of letters with k elements, do
    • if "a" is present in c, then
      • contain := contain + 1
    • total := total + 1
  • return contain/total

Example

Let us see the following implementation to get better understanding −

from itertools import combinations
def solve(letters, k):
   contain = 0
   total = 0

   for c in combinations(letters, k):
      if "a" in c:
         contain += 1
      total += 1
return contain/total

letters = ['a', 'c', 'a', 'b', 'l', 'a', 'b', 'z']
k = 2
print(solve(letters, k))

Input

['a', 'c', 'a', 'b', 'l', 'a', 'b', 'z'], 2

Output

0

Advertisements