Python uses the random and tertools modules to solve some typical probability problems

Source: Internet
Author: User
This article mainly introduces Python's use of the random and tertools modules to solve some classic probability problems. This article describes the use of the random and tertools modules to solve the problems of goat door, playing cards, and birthday paradox, for more information, see Common functions in the random module

The code is as follows:


Random ()
Returns a real number within the range [0, 1;
Uniform (a, B)
Returns a real number in the range [a, B;
Randint (a, B)
Returns an integer in the range [a, B;
Choice (sequence)
Returns an element in the sequence. the sequence is an ordered sequence, such as list, string, or tuple;
Randrange ([start], stop [, step])
It is equivalent to choice (range ([start], stop [, step]);
Shuffle (sequence [, random])
No return value, used to disrupt the arrangement order of elements in sequence;
Sample (sequence, n)
Returns a shard consisting of n sequence elements. the sequence can also be set.

Use itertools to get arrangement and combination

The code is as follows:


Permutations (sequence, k ))
Obtain all the arrays containing k elements from the sequence.

Combinations (sequence, k ))
Obtain all the combinations containing k elements from the sequence.

Goat door problems

There is a lottery show where there are three closed doors on the stage, one behind the door is parked with a car, and the other behind the door is goat. only the host knows what is behind each door. The contestant can select a door. before opening it, the host opens another door, revealing the goat behind the door, and then allows the contestant to change his choice. The question is: Can contestants increase their chances of winning a car after selecting a new one?

Many times, we do not know whether our theoretical analysis is correct or not. However, if we know the law of large numbers in probability theory and happen to understand a little programming, we can use computers to repeatedly simulate events to solve the problem. The Python 3.x solution to this problem is as follows:

The code is as follows:


From random import *

Def once (doors = 3): # simulate an event
Car = randrange (doors) # A car stops behind a door
Man = randrange (doors) # contestants select a door in advance
Return car = man # Do contestants first choose to get to the car?

H = 0 # The number of times you choose to win the car
C = 0 # change the number of times you choose to win a car
Times = int (1e6) # Number of repeated experiments

For I in range (times ):
If once (): h + = 1
Else: c ++ = 1

Print ("maintain selection:", h/times * 100, "% \ n change selection:", c/times * 100, "% ")

Running result:

Maintenance Options: 33.268%
Change selection: 66.732%

Playing cards

Probability theory brings us a lot of extraordinary results, especially conditional probabilities. For example:

One of the four members said that I had A in my hand. What is the probability that he has more than one?
One of the four members said that I had A black peach in my hand. What is the probability that he has more than one?

The code is as follows:


From random import *

Cards = [I for I in range (52)]
Counter = [0, 0, 0, 0]

Def once (): #0 indicates Peach
Global cards
Ace = set (sample (cards, 13) & {0, 1, 2, 3}
Return len (ace), 0 in ace

For I in range (int (1e6 )):
A, s = once () # a indicates the number of A, and s indicates whether there is A peach
If:
Counter [1] + = 1
If s: counter [3] + = 1
If a> 1:
Counter [0] + = 1
If s: counter [2] + = 1

Print ('scenario 1: ', counter [0]/counter [1],' \ n Case 2: ', counter [2]/counter [3])

Running result:

Case 1: 0.3694922900321386
Case 2: 0.5613778028656186

An interesting thing came out: if this person announced the color of A in his hand, the probability of holding multiple A in his hand would be greatly increased. But how can this be understood?

One family has two children. one is known to be a girl, and the other is probably a girl.

Every time someone posted a post on the Internet raises a paradox related to conditional probability, it will always attract numerous onlookers and debates, even if the essence of these problems is the same. This topic is undoubtedly one of the most controversial issues.

The analysis on the Internet looks like a decent one. some people who are confused may be confused. I think this is the right one for a while, and I think it is the right one for a while. Now, if I don't analyze those principles for you, I will use a computer to simulate the problem, so that you can come to a conclusion without understanding the cause.

The code is as follows:


From random import * #0 indicates girl, 1 indicates boy

Family = (lambda n: [{randrange (2), randrange (2)} for I in range (n)]) (int (1e6 ))

Both = family. count ({0}) # Number of girls' families
Exist = len (family)-family. count ({1}) # Number of families with girls

Print (both/exist)


Running result:

The code is as follows:


0.33332221770186543


Without those profound analysis processes, a few lines of code will give you the answer to the question. Presumably, this is also the benefit of computer introduction of mathematical computation and proof.

Birthday paradox

Everyone has a birthday, and occasionally meets people who have their own birthdays on the same day, but this fate does not seem to happen in life. Let's guess: What is the probability of such fate among 50 people? 10%, 20%, or 50%?

The code is as follows:


From random import *

Counter, times = 0, int (1e6)
For I in range (times ):
If len ({randrange (365) for I in range (50 )})! = 50: # People with the same natural day
Counter + = 1

Print ('probability of the same birthday among 50 people is: ', counter/times)


Running result:

The code is as follows:


The probability that 50 people have the same birthday is: 0.970109


In 50 people, the probability of the same birthday is as high as 97%, which is probably higher than the expectation of most people. We are not wrong. our intuition is wrong, and science and life are joking. Because of the obvious contradiction between the computing result and daily experience, this problem is called the "Birthday Paradox". it reflects the contradiction between rational computing and perceptual knowledge, and does not cause logical conflicts, therefore, it is not a paradox in the strict sense.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.