Un peu d'aléatoire

Un peu d'aléatoire

import random as rd
import matplotlib.pyplot as plt

## Pile ou face

def pileouface():
    if rd.random() < .5:
        return "Pile"
    else:
        return "Face"

def diag_pileouface(N):
    abs = ['Pile','Face','Rapport']
    result = [0,0,0]
    for _ in range(N):
        x = pileouface()
        if x=='Pile':
            result[0] += 1
        else:
            result[1] += 1
    result = [result[0]/N, result[1]/N, result[0]/result[1]]
    plt.clf()
    plt.bar(abs,result,color=['red',
     'blue'])
    xlocs=list(range(len(result)))
    for i, v in enumerate(result):
        plt.text(xlocs[i], v + 0.1, str(v), ha="center")
    plt.draw(); plt.show()
## Paradoxe de Monty-Hall

def montyhall(p):
    portes = ['Chevre' for _ in range(p)]
    voiture = rd.randint(0,p-1)
    portes[voiture] = 'Voiture'
    choix = rd.randint(0,p-1)
    if portes[choix] == 'Voiture':
        return 0
    else:
        return 1

def diag_montyhall(p,N):
    result = [0,0]
    for _ in range(N):
        k = montyhall(p)
        if k==0:
            result[1] += 1/N
        else:
            result[0] += 1/N
    plt.clf()
    plt.bar(['Change','Change pas'],result)
    plt.draw(); plt.show()

## Anniversaire

def unique(l):
    n = len(l)
    b = True
    i=0
    while b and i < n:
        if l[i] in l[i+1:]:
            b = False
        i = i + 1
    return b

def unique_rec(l):
    if l==[]:
        return True
    else:
        return (l[0] in l[1:]) and unique_rec(l[1:])

def anniversaire(n):
    anniv = [rd.randint(1,365) for _ in range(n)]
    if unique(anniv):
        return 1
    else:
        return 0

def diag_anniversaire(N):
    result = [0 for i in range(100)]
    for i in range(1,101):
        cmpt = 0
        for _ in range(N):
            if anniversaire(i) == 1:
                cmpt += 1/N
        result[i-1] = cmpt
    plt.clf()
    plt.bar(range(1,101),result)
    plt.plot([0,100],[.5,.5],c='r')
    plt.draw(); plt.show()

## Marches aleatoires

def MA_Z(N):
    pos= [0]
    for i in range(N-1):
        if rd.random() < .5:
            pos.append(pos[-1]+1)
        else:
            pos.append(pos[-1]-1)
    plt.clf()
    plt.plot(range(N),pos)
    plt.plot([0,N-1],[0,0])
    plt.draw(); plt.show()

def MA_Z2(N):
    x, y = 0., 0.
    x_plot = [x]
    y_plot = [y]
    for i in range(N):
        del_x,del_y=rd.randint(-1,1), rd.randint(-1,1)
        x, y = x + del_x, y + del_y
        x_plot.append(x)
        y_plot.append(y)
    plt.clf()
    plt.grid()
    plt.scatter(x_plot, y_plot,c= range(len(x_plot)), marker = '.', s=100)
    plt.colorbar()
    plt.axis('equal')
    plt.draw()
    plt.show()