Humair Ali
Humair Ali

Reputation: 71

how to use probability in python program

How do I calculate a probability in python?

Given the dataset A with the following values: [40, 10, 10, 20, 10]

How do I calculate the probability of receiving a value of 10? (10 occurs 3 times in total, 3/5 = 0.6

Here's the code I've written:

#!/usr/bin/env python3
"""reducer.py"""
import sys

# Create a dictionary to map marks
Marksprob = {}

# Get input from stdin
for line in sys.stdin:
    #Remove spaces from beginning and end of the line
    line = line.strip()

    # parse the input from mapper.py
    ClassA, Marks = line.split('\t', 1)


# Create function that returns probability percent rounded to one decimal place
def event_probability(event_outcomes, sample_space):
    probability = (event_outcomes / sample_space) * 100
    return round(probability, 1)


# Sample Space
ClassA = 25

# Determine the probability of drawing a heart
Marks = 12
grade_probability = event_probability(Marks, ClassA)

# Print each probability
print(str(grade_probability) + '%')

Upvotes: 0

Views: 928

Answers (1)

Jeanba
Jeanba

Reputation: 121

There are many ways to do this but here is a possible solution:

import numpy as np
import collections

npArray= np.array([40, 10, 10, 20, 10])
c=collections.Counter(npArray) # Generate a dictionary {"value":"nbOfOccurrences"}

arraySize=npArray.size
nbOfOccurrences=c[10] #assuming you want the proba to get 10

proba=(nbOfOccurrences/arraySize)*100
print(proba) #print 60.0

Upvotes: 2

Related Questions