Python USES the random and tertools modules to solve classical probability problems

  • 2020-04-02 14:31:12
  • OfStack

Common functions in the random module


random()
Returns a position interval [0,1] The real number inside;
uniform(a, b)
Returns a position interval [a,b] The real number inside;
randint(a, b)
Returns a position interval [a,b] An integer inside;
choice(sequence)
Returns a location sequence Where, sequence For an ordered sequence, such as list , string or tuple Such as the type;
randrange([start], stop[, step])
Equivalent to choice(range([start], stop[, step])) ;
shuffle(sequence [, random])
No return value for scrambling sequence The arrangement order of the elements in;
sample(sequence, n)
Return a return by n a sequence In which, sequence It can also be set Type.

Itertools is used to obtain permutations and combinations


permutations(sequence, k))
From the sequence sequence To be included in k All the permutations of the elements. combinations(sequence, k))
From the sequence sequence To be included in k All the combinations of the elements.

Sheep door problem

There was a raffle where there were three closed doors, a car behind one door and a goat behind the rest, and only the host knew what was behind each door. Contestants can choose a door, and before opening it, the host will open another door, exposing the goat behind it, and then allow the contestants to change their choice. The question is: can the racers increase their chances of winning the car by switching their choices?

There are many times when we don't know whether our theoretical analysis is correct or not, but knowing the law of large Numbers in probability theory and knowing a little bit about programming can undoubtedly solve problems by repeating computer simulations of events. The Python 3.x solution to this problem is as follows:


from random import * def once(doors = 3):  # A simulation of an event
 car = randrange(doors) # A car was parked behind a door
 man = randrange(doors) # Contestants select a door in advance
 return car == man # Whether the racers choose to get the car in the first place h = 0 # Stick to the number of times you won the car                    
c = 0 # Change the number of times you choose to win the car
times = int(1e6) # The number of times the experiment was repeated for i in range(times):
 if once(): h += 1
 else:  c += 1 print(" Maintain options: ",h/times*100,"%n Change of choice: ",c/times*100,"%")

Operation results:

Maintain choice: 33.268 %
Changed selection: 66.732 %

Poker problem

Probability theory brings us many strange and abnormal results, especially conditional probability. Such as:

There are four people playing poker, and one of them says, I have an A in my hand. What's the probability that he has more than one A on his hand?
Four people were playing poker, and one of them said, I have an ace of spades in my hand. What is the probability that he has more than one A on his hand?


from random import * cards = [i for i in range(52)]
counter = [0, 0, 0, 0] def once(): # 0 Said spades A
 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 said A The number of, s Indicates whether there is a spade A
 if a:
  counter[1] += 1
  if s: counter[3] += 1
 if a > 1:
  counter[0] += 1
  if s: counter[2] += 1 print(' Case 1: ', counter[0]/counter[1], 'n Situation 2: ', counter[2]/counter[3])

Operation results:

Case 1:0.3694922900321386
Case 2:0.5613778028656186

Here's the interesting thing: if this guy declares the suit of an A, the probability of holding more than one A in his hand goes up. But how to understand this?

If you have two children in a family and you know that one of them is a girl, the probability that the other one is also a girl

Every time someone posts a paradox related to conditional probability on the Internet, it always attracts numerous people to watch and debate, even if the essence of these questions is the same. This subject is undoubtedly one of the most debated issues.

Say that the analysis on the Internet are like a model, some originally are confused by the people of the dizzy, feel this right, and then feel that right. Now instead of giving you that analysis, I'm going to use a computer to simulate the problem so that you can come to a conclusion without knowing why.


from random import * # 0 For a girl, 1 Said the boy family = (lambda n :[{randrange(2),randrange(2)} for i in range(n)])(int(1e6)) both = family.count({0}) # All of them are girls
exist = len(family) - family.count({1}) # Number of families with girls print(both/exist)

Operation results:

0.33332221770186543

Without the esoteric analysis, a few lines of code would have given the answer to the question, presumably the benefit of introducing mathematical calculations and proofs into the computer.

The birthday paradox.

Everyone has a birthday, and occasionally you meet someone who shares it with you, but that doesn't seem to happen often in life. Let's take a guess: what's the probability of this happening to 50 people, 10%, 20% or 50%?


from random import * counter, times = 0, int(1e6)
for i in range(times):
 if len({randrange(365) for i in range(50)}) != 50: # There are people with the same birthday
  counter += 1 print(' in 50 The probability of having the same birthday among individuals is: ',counter/times)

Operation results:

in 50 The probability of having the same birthday among individuals is: 0.970109

The chance of having the same birthday is 97 per cent higher than most people would expect. We didn't make a mistake, our intuition was wrong, and science played a joke on life. It is precisely because of the apparent contradiction between the results of calculation and everyday experience that the problem is known as the "birthday paradox". Since it reflects the contradiction between rational calculation and perceptual knowledge, it does not cause a logical contradiction, so it is not a paradox in the strict sense.


Related articles: