Simple python examples

What you want What it is called Examples
Outputprintprinting1.py
randomwalk4.py
Loopsforloop1.py
dowhile.py
Command-line inputsys.argv commandline1.py
commandline2.py
randomwalk4.py
Function definitiondef fact.py
randomwalk4.py
randomwalk5.py
Reading in lines from standard inputsys.stdin reading1.py
Substitution using regular expressionsre reading1.py
length of a listlencommandline2.py
Convert string to integerintcommandline2.py
find something in listfind1.py
Sort a listsortsort1.py
Split a stringsplit1.py
Reading lines from a fileopen, readlinesreading2.py
Random numbersrandom.random()randomwalk4.py
randomwalk5.py
Automatic execution__name__, __main__randomwalk4.py
randomwalk5.py
Plotting graphsGnuplot randomwalk5.py
Plotting histogramspylab.hist histo1.py
Automated testingdoctest
(explanation)
DocExample.py
DocExample2.py
AlanDice.py
AlanDice2.py
decomposeSquares.py
Recursion decomposeSquares.py

randomwalk5.py

#!/usr/bin/env python
#                    Simple python examples
# python/centrallimit/randomwalk5.py
#                    David MacKay
#
# Make a walk with a fair coin, plotting 
# with Gnuplot the points reached at times
# 0, period, 2*period, 3*period...
#
# Usage:
# $ randomwalk5.py [R [T [period]]]
# Optional arguments:
#    R      = number of walks
#    T      = duration of walk
#    period = period between points shown
#
# Example: - make one walk
# $ randomwalk5.py 1 100 1
# - make 8 walks, and plot every 10th point
# $ randomwalk5.py 8 10000 10 
import random
import sys
import Gnuplot, Gnuplot.funcutils

def walk(T=10, period=1):
    """random walk with a fair coin"""
    x=0;     answer= [[0,0]]
    for t in xrange(T+1):
        u = random.random()
        if (u<= 0.5): x+=1 
        else:         x-=1 
        if (t%period == 0 ) :
            answer.append([ t+1 , x ])
    return answer

def makewalks(R=10, T=100,period=1):
    """Makes walks and plots them with gnuplot"""
    g = Gnuplot.Gnuplot(persist=1) #(debug=1, persist=1)
    g.title('Random walks') 
    g('set data style line') 

    for r in xrange(R):
        newwalk = walk(T,period)
        if(r==0): g.plot(newwalk)   ; pass
        else:     g.replot(newwalk) ; pass

if __name__ == '__main__':
    R=2
    T=100
    period=1
    if(len(sys.argv)>1):
        R=int(sys.argv[1])
    if(len(sys.argv)>2):
        T=int(sys.argv[2])
    if(len(sys.argv)>3):
        period=int(sys.argv[3])
    makewalks(R, T, period )
    pass

# This program illustrates
#  - how to read the command line
#  - how to plot lists of lists in gnuplot
#  - how to use random.random()
#      (there are many other random functions
#       available in python; random.random()
#       makes numbers between 0 and 1)
#  - how to write a package that contains
#       functions and that has a default behaviour
#       if run directly from a terminal
#       or from a python development environment


David MacKay / python resources /

David MacKay / Computational Physics wiki (UCAM only) / C++ resources /