当前位置:网站首页>freeCodeCamp----prob_ Calculator exercise
freeCodeCamp----prob_ Calculator exercise
2022-04-23 16:57:00 【Lily's autumn】
Catalog
2.2 Create a experiment function ( Not Hat class Inside )
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
边栏推荐
- PyMySQL
- Nacos + aspnetcore + Ocelot actual combat code
- oracle 中快速获取表的列名列表
- 无线鹅颈麦主播麦手持麦无线麦克风方案应当如何选择
- Idea of batch manufacturing test data, with source code
- SPC introduction
- MySql主从复制
- How to implement distributed locks with redis?
- MySQL master-slave configuration under CentOS
- English | day15, 16 x sentence true research daily sentence (clause disconnection, modification)
猜你喜欢
How to build tiktok user trust and drive fan growth
英语 | Day15、16 x 句句真研每日一句(从句断开、修饰)
Pycham connects to the remote server and realizes remote debugging
PyMySQL
How much do you know about the process of the interview
Use case labeling mechanism of robot framework
loggie 源码分析 source file 模块主干分析
ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
JMeter installation tutorial and solutions to the problems I encountered
MySQL master-slave synchronization pit avoidance version tutorial
随机推荐
STM32__ 03 - beginner timer
Get the column name list of the table quickly in Oracle
Sub database and sub table & shardingsphere
AIOT产业技术全景结构-数字化架构设计(8)
ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
An essay on the classical "tear down the wall in thinking"
Custom implementation of Baidu image recognition (instead of aipocr)
How to choose the wireless gooseneck anchor microphone and handheld microphone scheme
Paging the list collection
Linux MySQL data timing dump
Calculation formula related to tolerance analysis
Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
MySQL master-slave configuration under CentOS
MySQL restores data through binlog file
Smart doc + Torna generate interface document
英语 | Day15、16 x 句句真研每日一句(从句断开、修饰)
Copy constructor shallow copy and deep copy
Use case labeling mechanism of robot framework
True math problems in 1959 college entrance examination
PostgreSQL column storage and row storage