Monty Hall Python

Monty Hall problem simulation.
Player picks one of three doors (to win a car). Without opening the players door, the host opens a non-winning door (or win a goat). The player then can switch to the other closed door and stay with the first choice.

import random

def main(trials=12345, number_doors=3):
    # SHOW THE RANDOMNESS OF THE GAME SETUP
    show_game_randomness(trials, number_doors)
    
    # TEST NEVER SWITCHING AND ALWAYS SWITCHING
    # TRY NEVER SWITCHING
    trues = 0
    for trial in xrange(trials):
        is_car = play_a_game(SWITCH=False, number_doors=number_doors)
        if is_car: trues += 1
    print '{0} games and never switching: {1} wins ({2:.2%})'.format(
           trials, trues, trues/float(trials))
    # TRY ALWAYS SWITCHING
    trues = 0
    for trial in xrange(trials):
        is_car = play_a_game(SWITCH=True, number_doors=number_doors)
        if is_car: trues += 1
    print '{0} games and always switching: {1} wins ({2:.2%})'.format(
           trials, trues, trues/float(trials))
    
    
def play_a_game(SWITCH=False, number_doors=3):
    doors = newgame(number_doors)
    whose_door = ['']*number_doors
    # PLAYER SELECTS A DOOR
    whose_door[random.randint(0,number_doors-1)] = 'player'
    
    # HOST SHOWS A GOAT (SELECTS A GOAT DOOR)
    while True:
        host_sel = random.randint(0,number_doors-1)
        if doors[host_sel] != 'car' and whose_door[host_sel] != 'player':
            whose_door[host_sel] = 'host'
            break
        
    # SWITCH DOORS?
    if SWITCH:
        while True:
            player_sel = random.randint(0,number_doors-1)
            if whose_door[player_sel] != 'host' and whose_door[player_sel] != 'player':
                break
        whose_door[whose_door.index('player')] = 'nevermind'
        whose_door[player_sel] = 'player'
        
    # RETURN RESULT
    return True if doors[whose_door.index('player')] == 'car' else False
        
     
def newgame(number_doors=3):
    car_index = random.randint(0,number_doors-1)
    doors = ['goat']*number_doors
    doors[car_index] = 'car'
    return doors
    
    
def show_game_randomness(trials, number_doors=3):
    trial_results = [0]*number_doors    
    while True:
        doors = newgame(number_doors)
        trial_results[doors.index('car')] += 1
        
        if sum(trial_results) >= trials:
            print 'Car occurance:',
            print trial_results, 'times.',
            print ['{0:.2%}'.format(x/float(sum(trial_results))) for x in trial_results]
            break


if __name__ == '__main__':
    main()

When I read this problem and how switching doors is the best solution, it was a little hard to believe. I realized why switching is a good idea when programming the host’s selection process to show a goat. Since 2/3rds of the time, the host is constrained in his choice of the two remaining doors, therefor, 2/3rds of the time, the car is behind the door the host does not pick.

Saving a canvas animation

The only built-in image save function for Tkinter canvas is a postscript save. This didn’t work for me and instead of finding out why, I thought of another way which works great.
Create a frameless canvas window using ‘overrideredirect(1)’, place the canvas in the top corner and use PIL’s ImageGrab and save the images. Finally, ‘destroy’ the window when finished, since there is no kill button in the top corner. Here is an example that animates a polygon moving on the canvas.

from Tkinter import *
from PIL import ImageGrab
from numpy import array
import os


class App(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.overrideredirect(1)
        
        self.width = 900
        self.height = 640
        self.initialize()
        
    def initialize(self):
        self.c = Canvas(self, width=self.width, height=self.height, background='white')
        self.c.pack(side=RIGHT, expand=YES, fill=BOTH)
        self.update()
        
        self.run_anim()
        self.destroy()
        
        
    def run_anim(self):
        print os.getcwd()
        c = self.c
        polyo = array([34,60,226,15,419,60,359,151,91,151])
        polyd = array([205,253,296,187,388,253,353,360,239,360])
        trantime = 20
        for i in xrange(trantime):
            c.delete('pol')
            ptrans = (float(i)/trantime)*polyd+(trantime-float(i))/trantime*polyo
            c.create_polygon(list(ptrans), width=4, outline='black', fill='red', tags='pol')


            self.update()
            savename = 'im_{0:0>6}'.format(i)
            ImageGrab.grab((0,0,900,640)).save(savename + '.jpg')
            

app = App(None)
app.mainloop()

Skewness and Kurtosis

http://www.dreamincode.net/code/snippet3048.htm

 

Found a code for skewness and kurtosis. Just putting it here for reference.

from math import *
from Numeric import *
n=input("Enter the number of class:")
h=input("Enter class interval:")
sum_f=0
sum_fm=0
total1=0
total2=0
total3=0
a=zeros(n,Int)
b=zeros(n,Int)
for i in range(n):
    print "For class-%s"%(i+1)
    f=input("Frequency:")
    l=input("Lower limit:")
    u=l+h    #upper limit
    ul=(l+u)/2.0	#mean of upper and lower limit
    ful=f*ul	#multiplication of frequency and mean
    a[i]=ul
    b[i]=f
    sum_f=f+sum_f
    sum_fm=ful+sum_fm
x=sum_fm/sum_f		#arithmetic mean
for i in range(n):
    d=a[i]-x
    v1=pow(d,2)*b[i]
    v2=pow(d,3)*b[i]
    v3=pow(d,4)*b[i]
    total1=v1+total1
    total2=v1+total2
    total3=v1+total3    m2=total1/sum_f    #2nd moment
m3=total2/sum_f    #3rd moment
m4=total3/sum_f    #4th moment
s=pow(m3,2)/pow(m2,3)    #skewness
k=m4/pow(m2,2)    #kurtosis
print "The skewness is %s & kurtosis is %s"%(s,k)

print(“Hello world!”)

For the first entry of my programming activities record , I will start by posting my current script template. I plan on periodically updating this as I learn more about Python, but I guessing it won’t change much from this format. Maybe I should put it on a page instead of post.

_____________template.py_______________

#!/usr/bin/env python
# -*- coding: utf-8 -*-
“””
Created on %(date)s

@author: Ripley6811

@abstract:

@input: none

@output: none

@acknowledgments:
“””
#from numpy import * #imports ndarray(), arange(), zeros(), ones(), and other array methods
#from visual import * #imports NumPy.*, SciPy.*, and Visual objects (sphere, box, etc.)
#import matplotlib.pyplot as plot #use plot(x,y) and show() for plotting
#from pylab import * #imports NumPy.*, SciPy.*, and matplotlib.*

def main():

“””Description of main()”””

if __name__ == ‘__main__’:

main()

”’######################################
linspace(0,2,9) > array of 9 numbers from 0 to 2
zeros( (10,10,10) ) > a 3-d array of 0.0 (pass a list)
ones( (3,4,5) ) > a 3-d array of 1.0’s
”’######################################