当前位置:网站首页>freeCodeCamp----prob_ Calculator exercise

freeCodeCamp----prob_ Calculator exercise

2022-04-23 16:57:00 Lily's autumn

Catalog

1 Subject requirements

2 Detailed requirements

2.1 Create a Hat class

2.2 Create a experiment function ( Not Hat class Inside )

2.3 Illustrate with examples

3 Source code comments


1 Subject requirements

introduce : Suppose there is a hat , There are 5 A blue ball ,4 A red ball ,2 A green ball .

If you take it randomly 4 A ball , It contains at least 1 Red balls and 2 What is the probability of a green ball ?

subject : Write a program to calculate the probability of randomly taking a certain number of balls from the hat .

2 Detailed requirements

2.1 Create a Hat class

This class Multiple parameters should be accepted , Balls that contain both color and number .

There may be the following ways , Examples are as follows :

hat1 = Hat(yellow=3, blue=2, green=6)
hat2 = Hat(red=5, orange=4)
hat3 = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)
hat1 = Hat(yellow=3, blue=2, green=6)
hat2 = Hat(red=5, orange=4)
hat3 = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)

this class Contains at least one ball , The passed in parameters need to be converted into contents,contents It's a list The elements are strings,

give an example , If your hat yes {"red": 2, "blue": 1}, contents It should be ["red", "red", "blue"].

class Should contain a draw Method , Accept from hat Take the number of balls taken out as a parameter , This method moves the ball from contends Remove , And not put it back , Returns a string array of these balls .

2.2 Create a experiment function ( Not Hat class Inside )

This function takes the following parameters :

hat:  hat Object contains the ball copied from the function ;

expected_balls: for instance , Take it out of the hat for calculation 2 The probability of a blue ball and a red ball ,expected_balls It should be set to : {"blue":2, "red":1};

num_balls_drawn: Every time experiment In the from hat The number of balls taken out ;

num_experiments: Number of experiments ( The more experiments , The more accurate the probability );

Return the probability value ;

2.3 Illustrate with examples

Suppose you include 6 A black ball 、4 Red balls and 3 Take it out of the hat of a green ball 5 A ball , Calculate at least 2 Red balls and 1 The probability of a green ball . For calculation , We carry out N Experiments , Count the number of times we get the desired ball , Then calculate the probability M/N, The number of balls is the same before each experiment , Take out a fixed number of balls , Check if the color of these balls is expected .

The following example shows that the number of experiments is 2000 When the time , How to call experiment function :( When the number is random , The probability of each run may vary slightly )

hat = Hat(black=6, red=4, green=3)

probability = experiment(hat=hat,
                  expected_balls={"red":2,"green":1},
                  num_balls_drawn=5,
                  num_experiments=2000)

hat = Hat(black=6, red=4, green=3)

probability = experiment(hat=hat,
                  expected_balls={"red":2,"green":1},
                  num_balls_drawn=5,
                  num_experiments=2000)

And consider using in prob_calculator.py The library imported at the beginning of the file .

3 Source code comments

Link to the original text :FreeCodeCamp----Scientific Computing with Python Projects - probability-calculator_m0_43406494 The blog of -CSDN Blog

import copy
import random
# Consider using the modules imported above.

#  common 2 Parameters  *args,**kwargs,*args Yes or no keyword parameters , For tuples ,**kw It's a keyword parameter , For dictionaries 
#  **kwargs:
#  The key sign is an asterisk **, The name is optional .
#  When the number of parameters in the incoming function is unknown but the name of the parameter needs to be known , Use **kw.
#  Several parameters passed into the function form a dictionary .


class Hat:
    def __init__(self, **balls):
        self.contents = []
        # i  The color of a ball 
        # balls[i] Indicates the number of color balls 
        # j A loop is represented in contents Add j An element of that color 
        for i in balls:
            # print('i:', i)
            for j in range(balls[i]):
                self.contents.append(i)
                # print('contents:', self.contents)

    def draw(self, number):
        if number >= len(self.contents):
            temp = self.contents.copy()
            self.contents.clear()
            return temp
        temp = []
        #  stay 0 To contents A random number is generated between the number of balls in the 
        #  As a subscript , Take out the corresponding ball contents[n] Put in temp Array 
        #  And from the original contents Delete in , Because it is not put back 
        for i in range(number):
            n = random.choice(range(0, len(self.contents)))
            temp.append(self.contents[n])
            self.contents.pop(n)
        return temp


# expected_balls It's a dictionary ,expected_balls[j] What you get is actually the number of balls per ball 
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    count = 0
    for i in range(num_experiments):
        hat_copy = copy.deepcopy(hat)
        drawn = hat_copy.draw(num_balls_drawn)
        for j in expected_balls:
            # print('expected_balls[j]:', expected_balls[j])
            # print('count(j):', drawn.count(j))
            if expected_balls[j] > drawn.count(j):
                count -= 1
                break
        count += 1
    return count/num_experiments

版权声明
本文为[Lily's autumn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555126911.html