Probability Calculator

JSaw
3 min readOct 28, 2021

--

Project 2 of 5 freeCodeCamp’s Scientific Computing with Python series

For the background of this series, please refer to the first article here.

For this project, we will be creating a class that stores a variety of balls and a method in the class that allows us to randomly draw out balls from the class. Then, we create a function that runs the method for a specific number of repeated times to get the total probability for a specific draw result that we want to test.

To summarize, this project creates mainly 2 things :-

  1. Class named “Hat”
  2. Function named “experiment”

1. Create class

Create a class that takes a variable number of arguments

In this project, we will be getting an indefinite number of variables, the color of the balls and the number of balls

The basics to create class below.

To have indefinite keyword arguments in your class, we can use **kwargs

Stuff the arguments to a “contents” instance variable

For this, I made “contents” as a list item and uses extend()to insert the arguments into the “contents” instance variable. Good to know the difference between append() vs extend()

Create method inside class that allows us to draw random results

For this, I used sample() function in random module

2. Create function

Basics of creating a function

Run loops by using how many times the loop should run

I used the for x in range() function

Create dictionary to store the results of the draw

I used the dict() to create temporary variable to store the results of each draw. After that to compare the results to the expected results and store to “M” variable. After that to divide the “M” variable with the “N” variable provided in the project.

Links to my other project articles in this Scientific Computing with Python series

--

--