+ All Categories
Home > Documents > ContentsYou can also run/debug a program within PyCharm by selecting an appropriate Run/Debug con...

ContentsYou can also run/debug a program within PyCharm by selecting an appropriate Run/Debug con...

Date post: 05-Feb-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
69
Introduction to Programming in Python Contents Preface 4 Programming Environment Setup 5 Data Files 6 1 Imperative Programming 7 1.1 Your First Programs .................................................. 7 1.1.1 helloworld.py ................................................. 7 1.1.2 useargument.py ................................................ 7 1.2 Basic Data Types .................................................... 7 1.2.1 dateformats.py ................................................ 7 1.2.2 sumofsquares.py ............................................... 8 1.2.3 quadratic.py ................................................. 8 1.2.4 leapyear.py .................................................. 8 1.3 Control Flow ...................................................... 9 1.3.1 grade.py .................................................... 9 1.3.2 flip.py ..................................................... 9 1.3.3 nhellos.py ................................................... 10 1.3.4 powersoftwo.py ................................................ 10 1.3.5 divisorpattern.py .............................................. 10 1.3.6 harmonic.py .................................................. 11 1.3.7 sqrt.py ..................................................... 11 1.3.8 binary.py ................................................... 12 1.3.9 gambler.py ................................................... 12 1.3.10 factors.py ................................................... 13 1.4 Collection Data Types ................................................. 13 1.4.1 sample.py ................................................... 13 1.4.2 couponcollector.py ............................................. 14 1.4.3 primesieve.py ................................................. 14 1.4.4 selfavoid.py ................................................. 15 1.5 Input and Output ................................................... 15 1.5.1 randomseq.py ................................................. 15 1.5.2 twentyquestions.py ............................................. 16 1.5.3 average.py ................................................... 17 1.5.4 rangefilter.py ................................................ 17 1.5.5 plotfilter.py ................................................. 17 1.5.6 bouncingball.py ............................................... 18 1.5.7 playthattune.py ............................................... 19 1.6 Case Study: What Makes Google Different? (PageRank Algorithm) ....................... 19 1.6.1 transition.py ................................................. 19 1.6.2 randomsurfer.py ............................................... 20 1.6.3 markov.py ................................................... 20 2 Procedural Programming 21 2.1 Defining Functions ................................................... 21 2.1.1 harmonicredux.py ............................................... 21 2.1.2 couponcollectorredux.py .......................................... 21 2.1.3 playthattunedeluxe.py ........................................... 22 2.2 Modules and Applications ............................................... 23 2.2.1 gaussiantable.py ............................................... 23 2.2.2 gaussian.py .................................................. 23 2.2.3 ifs.py ..................................................... 24 1 / 69
Transcript
  • Introduction to Programming in Python

    Contents

    Preface 4

    Programming Environment Setup 5

    Data Files 6

    1 Imperative Programming 71.1 Your First Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    1.1.1 helloworld.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.1.2 useargument.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    1.2 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.2.1 dateformats.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.2.2 sumofsquares.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.2.3 quadratic.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.2.4 leapyear.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    1.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3.1 grade.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3.2 flip.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3.3 nhellos.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.4 powersoftwo.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.5 divisorpattern.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.6 harmonic.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3.7 sqrt.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3.8 binary.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.9 gambler.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.10 factors.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    1.4 Collection Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.4.1 sample.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.4.2 couponcollector.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.4.3 primesieve.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.4.4 selfavoid.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    1.5 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.5.1 randomseq.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.5.2 twentyquestions.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.5.3 average.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.5.4 rangefilter.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.5.5 plotfilter.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.5.6 bouncingball.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.5.7 playthattune.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    1.6 Case Study: What Makes Google Different? (PageRank Algorithm) . . . . . . . . . . . . . . . . . . . . . . . 191.6.1 transition.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.6.2 randomsurfer.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.6.3 markov.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    2 Procedural Programming 212.1 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    2.1.1 harmonicredux.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.1.2 couponcollectorredux.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.1.3 playthattunedeluxe.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    2.2 Modules and Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.2.1 gaussiantable.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.2.2 gaussian.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.2.3 ifs.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    1 / 69

  • Introduction to Programming in Python

    2.2.4 matrix.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    2.3.1 factorial.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262.3.2 euclid.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.3.3 towersofhanoi.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.3.4 htree.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.3.5 fibonacci.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    2.4 Case Study: Fermi’s Paradox (Percolation Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.4.1 percolationio.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.4.2 percolation.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.4.3 visualize.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.4.4 estimate.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.4.5 percolationplot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    3 Object-oriented Programming 343.1 Using Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    3.1.1 potentialgene.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.1.2 alberssquares.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.1.3 luminance.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.1.4 grayscale.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.1.5 fade.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.1.6 cat.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.1.7 split.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

    3.2 Creating Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.2.1 timeops.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.2.2 stopwatch.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.2.3 bernoulli.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.2.4 histogram.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413.2.5 drunks.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.2.6 turtle.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

    3.3 Designing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.3.1 complex.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.3.2 mandelbrot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.3.3 vector.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463.3.4 sketch.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.3.5 comparedocuments.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.3.6 counter.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.3.7 country.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.8 fibonaccisequence.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.3.9 words.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523.3.10 errorhandling.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    3.4 Case Study: The Music of the Spheres (N -body Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533.4.1 body.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533.4.2 universe.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543.4.3 nbody.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    4 Data Structures and Algorithms 564.1 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    4.1.1 threesum.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564.2 Searching and Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

    4.2.1 linearsearch.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574.2.2 binarysearch.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574.2.3 zipf.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584.2.4 insertion.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    2 / 69

  • Introduction to Programming in Python

    4.2.5 merge.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604.3 Stacks, Queues, and Symbol Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

    4.3.1 reverse.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614.3.2 arraystack.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614.3.3 kthfromlast.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624.3.4 arrayqueue.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.3.5 frequencycounter.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644.3.6 symboltable.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    4.4 Case Study: Six Degrees of Separation (Small-world Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . 664.4.1 graph.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664.4.2 pathfinder.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674.4.3 smallworld.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684.4.4 performer.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    3 / 69

  • Introduction to Programming in Python

    Preface

    This document contains listings of the programs I use to teach an introductory course on programming in Python. Most ofthe programs are from the excellent textbook Introduction to Programming in Python: An Interdisciplinary Approach W byRobert Sedgewick, Kevin Wayne, and Robert Dondero. The programs have been modified for clarity and consistency. Thelisting for each program includes colorized Python code for the program with line numbers, and a terminal session showingthe command to run the program along with the program output.

    The programs are available as a PyCharm project (https://www.swamiiyer.net/teaching/ipp.zip W). Consult the section ProgrammingEnvironment Setup for instructions on how to setup your personal computer with the environment needed to run the programs.To open the project, launch PyCharm and open ~/workspace/ipp/programs. You can run a program on the PyCharm terminal, asfollows:

    & ~/workspace/ipp/programs

    $ python3 helloworld.pyHello , World$ _

    You can also run/debug a program within PyCharm by selecting an appropriate Run/Debug configuration and clicking Runor Debug.

    Input data files are available under the data folder, also included in ipp.zip. The table in section Data Files lists the names ofthe data-driven programs, references to them within this document, and the relevant data files.

    4 / 69

    http://www.amazon.com/Introduction-Programming-Python-Interdisciplinary-Approach/dp/0134076435/https://www.swamiiyer.net/teaching/ipp.zip

  • Introduction to Programming in Python

    Programming Environment Setup

    In the following sections, when you run the suggested commands in the terminal, do not copy-paste the commands intothe terminal; type them into the terminal instead.

    On Ubuntu Linux

    1. Launch a terminal and run the following commands.

    & ~/

    1 $ cd $HOME2 $ sudo apt -get install python3 -pip python3 -tk3 $ sudo pip3 install numpy pygame4 $ mkdir lib workspace5 $ wget https ://www.swamiiyer.net/teaching/stdlib -python.zip6 $ unzip stdlib -python.zip -d lib7 $ rm stdlib -python.zip8 $ echo "export PYTHONPATH =.: $HOME/lib/stdlib -python" >> $HOME/. bashrc9 $ wget https ://www.swamiiyer.net/teaching/ipp.zip

    10 $ unzip ipp.zip -d workspace11 $ rm ipp.zip

    2. Download and install PyCharm (Community Edition) W.

    On Mac OS X

    1. Launch a terminal and run the following commands.

    & ~/

    1 $ cd $HOME2 $ /usr/bin/ruby -e "$(curl -fsSL https :// raw.githubusercontent.com/Homebrew/install/master/install )"3 $ brew install python4 $ pip install numpy pygame5 $ mkdir lib workspace6 $ wget https ://www.swamiiyer.net/teaching/stdlib -python.zip7 $ unzip stdlib -python.zip -d lib8 $ rm stdlib -python.zip9 $ echo "export PYTHONPATH =.: $HOME/lib/stdlib -python" >> $HOME/. bash_profile

    10 $ wget https ://www.swamiiyer.net/teaching/ipp.zip11 $ unzip ipp.zip -d lib12 $ rm ipp.zip

    2. Download and install PyCharm (Community Edition) W.

    On Windows

    1. Install Python 3 W.

    2. Launch a powershell terminal and run the following commands.

    & ~/

    1 $ pip3 install numpy pygame2 $ mkdir lib ,workspace3 $ wget -O stdlib -python.zip https ://www.swamiiyer.net/teaching/stdlib -python.zip4 $ Expand -Archive -LiteralPath stdlib -python.zip -DestinationPath lib5 $ rm stdlib -python.zip6 $ setx PYTHONPATH ".; $HOME\lib\stdlib -python"7 $ wget -O ipp.zip https ://www.swamiiyer.net/teaching/ipp.zip8 $ Expand -Archive -LiteralPath ipp.zip -DestinationPath workspace9 $ rm ipp.zip

    3. Download and install PyCharm (Community Edition) W. Launch PyCharm, go to Configure → Settings → Tools →Terminal and set Shell path to powershell.

    5 / 69

    https://www.jetbrains.com/pycharm/download/#section=linuxhttps://www.jetbrains.com/pycharm/download/#section=machttps://www.python.org/downloads/https://www.jetbrains.com/pycharm/download/#section=windows

  • Introduction to Programming in Python

    Data Files

    Program Reference Data Filesplotfilter.py 1.5.5 usa.txtplaythattune.py 1.5.7 ascale.txt, elise.txt, entertainer.txt, firstcut.txt, freebird.txt, looney.txt, stairwaytoheaven.txttransition.py 1.6.1 small.txt, medium.txtplaythattunedeluxe.py 2.1.3 ascale.txt, elise.txt, entertainer.txt, firstcut.txt, freebird.txt, looney.txt, stairwaytoheaven.txtifs.py 2.2.3 barnsley.txt, coral.txt, culcita.txt, cyclosorus.txt, dragon.txt, fishbone.txt, floor.txt, koch.txt,

    sierpinski.txt, spiral.txt, swirl.txt, tree.txt, zigzag.txtpercolation.py 2.4.2 test5.txt, test8.txtgrayscale.py 3.1.4 darwin.jpg, darwin.png, mandrill.png, mandrill.pngfade.py 3.1.5 darwin.jpg, darwin.png, mandrill.png, mandrill.pngcat.py 3.1.6 in1.txt, in2.txtsplit.py 3.1.7 amino.csv, djia.csv, elements.csv, ip-by-country.csv, ip.csv, morse.csv, phone-na.csvsketch.py 3.3.4 actg.txt, constitution.txt, djia.csv, huckfinn.txt, prejudice.txt, tale.txt, tomsawyer.txtcomparedocuments.py 3.3.5 documents.txt, actg.txt, constitution.txt, djia.csv, huckfinn.txt, prejudice.txt, tale.txt,

    tomsawyer.txt

    nbody.py 3.4.3 2bodytiny.txt, 2body.txt, 3body.txt, 4body.txtthreesum.py 4.1.1 1Kints.txt, 2Kints.txt, 4Kints.txt, 8Kints.txt, 16Kints.txt, 32Kints.txtlinearsearch.py 4.2.1 tinyW.txt, tinyT.txt, largeW.txt, largeT.txtbinarysearch.py 4.2.2 tinyW.txt, tinyT.txt, largeW.txt, largeT.txtzipf.py 4.2.3 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txtinsertion.py 4.2.4 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txtmerge.py 4.2.5 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txtarraystack.py 4.3.2 tobe.txtarrayqueue.py 4.3.4 tobe.txtfrequencycounter.py 4.3.5 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txtgraph.py 4.4.1 tinygraph.txt, routes.txtpathfinder.py 4.4.2 tinygraph.txt, routes.txtsmallworld.py 4.4.3 tinygraph.txt, routes.txtperformer.py 4.4.4 tinymovies.txt, movies.txt

    6 / 69

  • Introduction to Programming in Python

    1 Imperative Programming

    1.1 Your First Programs

    1.1.1 helloworld.py

    L helloworld.py

    1 # Writes the message ’Hello , World’ to standard output.23 import stdio45 stdio.writeln(’Hello , World ’)

    & ~/workspace/ipp/programs

    $ python3 helloworld.pyHello , World$ _

    1.1.2 useargument.py

    L useargument.py

    1 # Accepts a name as command -line argument; and writes a message containing that name to standard2 # output.34 import stdio5 import sys67 stdio.write(’Hi, ’)8 stdio.write(sys.argv [1])9 stdio.writeln(’. How are you?’)

    & ~/workspace/ipp/programs

    $ python3 useargument.py AliceHi, Alice. How are you?$ python3 useargument.py BobHi, Bob. How are you?$ python3 useargument.py CarolHi, Carol. How are you?$ _

    1.2 Basic Data Types

    1.2.1 dateformats.py

    L dateformats.py

    1 # Accepts d (str), m (str), and y (str) representing a date as command -line arguments; and writes2 # the date in different formats to standard output.34 import stdio5 import sys67 d = sys.argv [1]8 m = sys.argv [2]9 y = sys.argv [3]

    10 dmy = d + ’/’ + m + ’/’ + y11 mdy = m + ’/’ + d + ’/’ + y12 ymd = y + ’/’ + m + ’/’ + d13 stdio.writeln(dmy)14 stdio.writeln(mdy)15 stdio.writeln(ymd)

    & ~/workspace/ipp/programs

    $ python3 dateformats.py 14 03 187914/03/187903/14/18791879/03/14$ _

    7 / 69

  • Introduction to Programming in Python

    1.2.2 sumofsquares.py

    L sumofsquares.py

    1 # Accepts x (int) and y (int) as command -line arguments; and writes the sum of their squares to2 # standard output.34 import stdio5 import sys67 x = int(sys.argv [1])8 y = int(sys.argv [2])9 result = x * x + y * y

    10 stdio.writeln(result)

    & ~/workspace/ipp/programs

    $ python3 sumofsquares.py 3 425$ python3 sumofsquares.py 6 8100$ _

    1.2.3 quadratic.py

    L quadratic.py

    1 # Accepts a (float), b (float), and c (float) as command -line arguments; and writes the two roots2 # of the quadratic equation ax^2 + bx + c = 0 to standard output.34 import math5 import stdio6 import sys78 a = float(sys.argv [1])9 b = float(sys.argv [2])

    10 c = float(sys.argv [3])11 discriminant = b * b - 4 * a * c12 root1 = (-b + math.sqrt(discriminant )) / (2 * a)13 root2 = (-b - math.sqrt(discriminant )) / (2 * a)14 stdio.writeln(’Root # 1 = ’ + str(root1 ))15 stdio.writeln(’Root # 2 = ’ + str(root2 ))

    & ~/workspace/ipp/programs

    $ python3 quadratic.py 1 -5 6Root # 1 = 3.0Root # 2 = 2.0$ python3 quadratic.py 1 -1 -1Root # 1 = 1.618033988749895Root # 2 = -0.6180339887498949$ _

    1.2.4 leapyear.py

    L leapyear.py

    1 # Accepts y (int) as command -line argument representing a year; and writes to standard output2 # whether the year is a leap year or not.34 import stdio5 import sys67 y = int(sys.argv [1])8 result = y % 4 == 0 and y % 100 != 0 or y % 400 == 09 stdio.writeln(result)

    & ~/workspace/ipp/programs

    $ python3 leapyear.py 2020True$ python3 leapyear.py 1900False$ python3 leapyear.py 2000True

    8 / 69

  • Introduction to Programming in Python

    $ _

    1.3 Control Flow

    1.3.1 grade.py

    L grade.py

    1 # Accepts a percentage score (float) as command -line argument; and writes the corresponding2 # letter grade to standard output.34 import stdio5 import sys67 score = float(sys.argv [1])8 if score >= 93:9 stdio.writeln(’A’)

    10 elif score >= 90:11 stdio.writeln(’A-’)12 elif score >= 87:13 stdio.writeln(’B+’)14 elif score >= 83:15 stdio.writeln(’B’)16 elif score >= 80:17 stdio.writeln(’B-’)18 elif score >= 77:19 stdio.writeln(’C+’)20 elif score >= 73:21 stdio.writeln(’C’)22 elif score >= 70:23 stdio.writeln(’C-’)24 elif score >= 67:25 stdio.writeln(’D+’)26 elif score >= 63:27 stdio.writeln(’D’)28 elif score >= 60:29 stdio.writeln(’D-’)30 else:31 stdio.writeln(’F’)

    & ~/workspace/ipp/programs

    $ python3 grade.py 97A$ python3 grade.py 56F$ _

    1.3.2 flip.py

    L flip.py

    1 # Simulates a coin flip by writing ’Heads’ or ’Tails’ to standard output.23 import stdio4 import stdrandom56 result = ’Heads’ if stdrandom.bernoulli () else ’Tails ’7 stdio.writeln(result)

    & ~/workspace/ipp/programs

    $ python3 flip.pyHeads$ python3 flip.pyHeads$ python3 flip.pyTails$ _

    9 / 69

  • Introduction to Programming in Python

    1.3.3 nhellos.py

    L nhellos.py

    1 # Accepts n (int) as command -line argument; and writes n Hellos to standard output.23 import stdio4 import sys56 n = int(sys.argv [1])7 i = 18 while i

  • Introduction to Programming in Python

    12 else:13 stdio.write(’ ’)14 stdio.writeln(i)

    & ~/workspace/ipp/programs

    $ python3 divisorpattern.py 20* * * * * * * * * * * * * * * * * * * * 1* * * * * * * * * * * 2* * * * * * * 3* * * * * * * 4* * * * * 5* * * * * * 6* * * 7* * * * * 8* * * * 9* * * * * 10* * 11* * * * * * 12* * 13* * * * 14* * * * 15* * * * * 16* * 17* * * * * * 18* * 19* * * * * * 20$ _

    1.3.6 harmonic.py

    L harmonic.py

    1 # Accepts n (int) as command -line argument; and writes the nth harmonic number (1 + 1/2 + ... +2 # 1/n) to standard output.34 import stdio5 import sys67 n = int(sys.argv [1])8 total = 0.09 for i in range(1, n + 1):

    10 total += 1 / i11 stdio.writeln(total)

    & ~/workspace/ipp/programs

    $ python3 harmonic.py 102.9289682539682538$ python3 harmonic.py 10007.485470860550343$ python3 harmonic.py 100009.787606036044348$ _

    1.3.7 sqrt.py

    L sqrt.py

    1 # Accepts c (float) as command -line argument; and writes the square root of c to standard output ,2 # computed using Newton ’s method.34 import stdio5 import sys67 c = float(sys.argv [1])8 EPSILON = 1e-159 t = c

    10 while abs(1 - c / (t * t)) > EPSILON:11 t = (c / t + t) / 212 stdio.writeln(t)

    11 / 69

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 sqrt.py 21.414213562373095$ python3 sqrt.py 10000001000.0$ python3 sqrt.py 0.40.6324555320336759$ python3 sqrt.py 10485751023.9995117186336$ python3 sqrt.py 166644444082.2106756021303$ python3 sqrt.py 1e-509.999999999999999e-26$ _

    1.3.8 binary.py

    L binary.py

    1 # Accepts n (int) as command -line argument; and writes the binary representation of n to standard2 # output.34 import stdio5 import sys67 n = int(sys.argv [1])8 v = 19 while v 0:12 if n < v:13 stdio.write(’0’)14 else:15 stdio.write(’1’)16 n -= v17 v //= 218 stdio.writeln ()

    & ~/workspace/ipp/programs

    $ python3 binary.py 1910011$ python3 binary.py 25511111111$ python3 binary.py 5121000000000$ python3 binary.py 1000000000111011100110101100101000000000$ _

    1.3.9 gambler.py

    L gambler.py

    1 # Accepts stake (int), goal (int), and trials (int) as command -line arguments; runs trials2 # experiments (dollar bets) that start with stake dollars and terminate on 0 dollars or goal; and3 # writes the percentage of wins and the average number of bets per experiment to standard output.45 import stdio6 import sys7 import stdrandom89 stake = int(sys.argv [1])

    10 goal = int(sys.argv [2])11 trials = int(sys.argv [3])12 bets = 013 wins = 014 for t in range(trials ):15 cash = stake16 while 0 < cash < goal:17 bets += 118 if stdrandom.bernoulli ():19 cash += 120 else:21 cash -= 1

    12 / 69

  • Introduction to Programming in Python

    22 if cash == goal:23 wins += 124 stdio.writeln(str (100 * wins // trials) + ’% wins’)25 stdio.writeln(’Avg # bets: ’ + str(bets // trials ))

    & ~/workspace/ipp/programs

    $ python3 gambler.py 10 20 100046% winsAvg # bets: 97$ python3 gambler.py 50 250 10019% winsAvg # bets: 12069$ python3 gambler.py 500 2500 10019% winsAvg # bets: 1155781$ _

    1.3.10 factors.py

    L factors.py

    1 # Accepts n (int) as command -line argument; and writes the prime factors of n to standard output.23 import stdio4 import sys56 n = int(sys.argv [1])7 factor = 28 while factor * factor 1:14 stdio.write(n)15 stdio.writeln ()

    & ~/workspace/ipp/programs

    $ python3 factors.py 37572082 2 2 7 13 13 397$ python3 factors.py 28799483722231117 1739347 9739789$ _

    1.4 Collection Data Types

    1.4.1 sample.py

    L sample.py

    1 # Accepts m (int) and n (int) as command -line arguments; and writes to standard output a random2 # sample of m integers in the range [0, n), with no duplicates.34 import stdarray5 import stdio6 import stdrandom7 import sys89 m = int(sys.argv [1])

    10 n = int(sys.argv [2])11 perm = stdarray.create1D(n, 0)12 for i in range(n):13 perm[i] = i14 for i in range(m):15 r = stdrandom.uniformInt(i, n)16 temp = perm[r]17 perm[r] = perm[i]18 perm[i] = temp19 for i in range(m):20 stdio.write(str(perm[i]) + ’ ’)21 stdio.writeln ()

    13 / 69

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 sample.py 6 1610 7 11 1 8 5$ python3 sample.py 10 1000258 802 440 28 244 256 564 11 515 24$ python3 sample.py 20 2015 11 13 1 5 8 16 7 0 4 10 18 19 14 3 12 2 6 9 17$ _

    1.4.2 couponcollector.py

    L couponcollector.py

    1 # Accepts n (int) as a command -line argument; and writes to standard output the number of coupons2 # you collect before obtaining one of each of n types.34 import stdarray5 import stdio6 import stdrandom7 import sys89 n = int(sys.argv [1])

    10 count = 011 collectedCount = 012 isCollected = stdarray.create1D(n, False)13 while collectedCount < n:14 value = stdrandom.uniformInt (0, n)15 count += 116 if not isCollected[value]:17 collectedCount += 118 isCollected[value] = True19 stdio.writeln(count)

    & ~/workspace/ipp/programs

    $ python3 couponcollector.py 10006276$ python3 couponcollector.py 10007038$ python3 couponcollector.py 100000013401736$ _

    1.4.3 primesieve.py

    L primesieve.py

    1 # Accepts n (int) as command -line argument; and writes the number of primes

  • Introduction to Programming in Python

    $ _

    1.4.4 selfavoid.py

    L selfavoid.py

    1 # Accepts n (int) and trials (int) as command -line arguments; and writes to standard output the2 # percentage of dead ends encountered out of trials self -avoiding random walks on an n-by-n lattice.34 import stdarray5 import stdio6 import stdrandom7 import sys89 n = int(sys.argv [1])

    10 trials = int(sys.argv [2])11 deadEnds = 012 for t in range(trials ):13 a = stdarray.create2D(n, n, False)14 x = n // 215 y = n // 216 while x > 0 and x < n - 1 and y > 0 and y < n - 1:17 a[x][y] = True18 if a[x - 1][y] and a[x + 1][y] and a[x][y - 1] and a[x][y + 1]:19 deadEnds += 120 break21 r = stdrandom.uniformInt (1, 5)22 if r == 1 and not a[x + 1][y]:23 x += 124 elif r == 2 and not a[x - 1][y]:25 x -= 126 elif r == 3 and not a[x][y + 1]:27 y += 128 elif r == 4 and not a[x][y - 1]:29 y -= 130 stdio.writeln(str (100 * deadEnds // trials) + ’% dead ends’)

    & ~/workspace/ipp/programs

    $ python3 selfavoid.py 5 10000% dead ends$ python3 selfavoid.py 20 100033% dead ends$ python3 selfavoid.py 40 100078% dead ends$ python3 selfavoid.py 80 100098% dead ends$ _

    1.5 Input and Output

    1.5.1 randomseq.py

    L randomseq.py

    1 # Accepts n (int), lo (float), and hi (float) as command -line arguments; and writes to standard2 # output n random floats in the range [lo, hi), each up to 2 decimal places.34 import stdio5 import stdrandom6 import sys78 n = int(sys.argv [1])9 lo = float(sys.argv [2])

    10 hi = float(sys.argv [3])11 for i in range(n):12 r = stdrandom.uniformFloat(lo , hi)13 stdio.writef(’%.2f\n’, r)

    & ~/workspace/ipp/programs

    $ python3 randomseq.py 10 100 200186.69102.34176.05

    15 / 69

  • Introduction to Programming in Python

    182.78161.95169.34155.65154.96194.41103.91$ _

    1.5.2 twentyquestions.py

    L twentyquestions.py

    1 # Generates a random integer; repeatedly accepts user guesses from standard input; writes ’Too2 # low’ or ’Too high’ to standard output , as appropriate , in response to each guess; and writes3 # ’You win!’ to standard output and exits when the user’s guess is correct.45 import stdio6 import stdrandom78 RANGE = 10000009 secret = stdrandom.uniformInt (1, RANGE + 1)

    10 stdio.writef(’I am thinking of a secret number between 1 and %d\n’, RANGE)11 guess = 012 while guess != secret:13 stdio.write(’What is your guess? ’)14 guess = stdio.readInt ()15 if guess < secret:16 stdio.writeln(’Too low’)17 elif guess > secret:18 stdio.writeln(’Too high’)19 else:20 stdio.writeln(’You win!’)

    & ~/workspace/ipp/programs

    $ python3 twenty questionsI am thinking of a secret number between 1 and 1000000What is your guess? 500000Too lowWhat is your guess? 750000Too highWhat is your guess? 625000Too highWhat is your guess? 562500Too highWhat is your guess? 531250Too highWhat is your guess? 515625Too highWhat is your guess? 507812Too highWhat is your guess? 503906Too highWhat is your guess? 501953Too highWhat is your guess? 500977Too lowWhat is your guess? 501465Too lowWhat is your guess? 501709Too highWhat is your guess? 501587Too lowWhat is your guess? 501648Too lowWhat is your guess? 501679Too lowWhat is your guess? 501694Too highWhat is your guess? 501686You win!$ _

    16 / 69

  • Introduction to Programming in Python

    1.5.3 average.py

    L average.py

    1 # Accepts floats from standard input; and writes their average to standard output.23 import stdio45 total = 0.06 count = 07 while not stdio.isEmpty ():8 x = stdio.readFloat ()9 total += x

    10 count += 111 average = total / count12 stdio.writeln(’Average is ’ + str(average ))

    & ~/workspace/ipp/programs

    $ python3 average.py10.0 5.0 6.0 3.0 7.0 32.0

    Average is 10.5$ _

    1.5.4 rangefilter.py

    L rangefilter.py

    1 # Accepts lo (int) and hi (int) as command -line arguments and integers from standard input; and2 # writes to standard output those integers that are in the range [lo, hi].34 import stdio5 import sys67 lo = int(sys.argv [1])8 hi = int(sys.argv [2])9 while not stdio.isEmpty ():

    10 x = stdio.readInt ()11 if x >= lo and x

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 plotfilter.py < ../ data/usa.txt$ _

    1.5.6 bouncingball.py

    L bouncingball.py

    1 # Draws a bouncing ball using standard draw.23 import stddraw45 RADIUS = 0.056 DT = 1.07 PAUSE = 208 stddraw.setXscale (-1.0, 1.0)9 stddraw.setYscale (-1.0, 1.0)

    10 rx = 0.48011 ry = 0.86012 vx = 0.01513 vy = 0.02314 while True:15 if abs(rx + vx * DT) + RADIUS > 1.0:16 vx = -vx17 if abs(ry + vy * DT) + RADIUS > 1.0:18 vy = -vy19 rx += vx * DT20 ry += vy * DT21 stddraw.clear(stddraw.WHITE)22 stddraw.filledCircle(rx , ry, RADIUS)23 stddraw.show(PAUSE)

    & ~/workspace/ipp/programs

    $ python3 bouncingball.py$ _

    18 / 69

  • Introduction to Programming in Python

    1.5.7 playthattune.py

    L playthattune.py

    1 # Accepts sound samples , each characterized by a pitch and a duration , from standard input; and2 # plays the sound using standard audio.34 import math5 import stdarray6 import stdaudio7 import stdio89 SPS = 44100

    10 NOTES_ON_SCALE = 1211 CONCERT_A = 440.012 while not stdio.isEmpty ():13 pitch = stdio.readInt ()14 duration = stdio.readFloat ()15 hz = CONCERT_A * math.pow(2, pitch / NOTES_ON_SCALE)16 n = int(SPS * duration)17 note = stdarray.create1D(n + 1, 0.0)18 for i in range(n + 1):19 note[i] = math.sin(2 * math.pi * i * hz / SPS)20 stdaudio.playSamples(note)21 stdaudio.wait()

    & ~/workspace/ipp/programs

    $ python3 playthattune.py < ../ data/elise.txt$ _

    1.6 Case Study: What Makes Google Different? (PageRank Algorithm)

    1.6.1 transition.py

    L transition.py

    1 # Accepts links from standard input; and writes the corresponding transition matrix to standard2 # output , computed using the 90-10 rule.34 import stdarray5 import stdio67 n = stdio.readInt ()8 outDegrees = stdarray.create1D(n, 0)9 linkCounts = stdarray.create2D(n, n, 0)

    10 while not stdio.isEmpty ():11 i = stdio.readInt ()12 j = stdio.readInt ()13 outDegrees[i] += 114 linkCounts[i][j] += 115 stdio.writeln(str(n) + ’ ’ + str(n))16 for i in range(n):17 for j in range(n):18 p = 0.9 * linkCounts[i][j] / outDegrees[i] + 0.1 / n

    19 / 69

  • Introduction to Programming in Python

    19 stdio.writef(’%8.5f’, p)20 stdio.writeln ()

    & ~/workspace/ipp/programs

    $ python3 transition.py < ../ data/small.txt5 50.02000 0.92000 0.02000 0.02000 0.020000.02000 0.02000 0.38000 0.38000 0.200000.02000 0.02000 0.02000 0.92000 0.020000.92000 0.02000 0.02000 0.02000 0.020000.47000 0.02000 0.47000 0.02000 0.02000

    $ _

    1.6.2 randomsurfer.py

    L randomsurfer.py

    1 # Accepts moves (int) as command -line argument and a transition matrix from standard input;2 # performs moves transitions as prescribed by the transition matrix; and writes the relative3 # frequency of hitting each page to standard output.45 import stdarray6 import stdio7 import stdrandom8 import sys9

    10 moves = int(sys.argv [1])11 transitionMatrix = stdarray.readFloat2D ()12 n = len(transitionMatrix)13 hits = stdarray.create1D(n, 0)14 page = 015 for m in range(moves ):16 page = stdrandom.discrete(transitionMatrix[page])17 hits[page] += 118 for hit in hits:19 stdio.writef("%8.5f", hit / moves)20 stdio.writeln ()

    & ~/workspace/ipp/programs

    $ python3 transition.py < ../ data/small.txt | python3 randomsurfer.py 1000.29000 0.30000 0.09000 0.25000 0.07000

    $ python3 transition.py < ../ data/small.txt | python3 randomsurfer.py 100000.27320 0.26840 0.14590 0.24550 0.06700

    $ python3 transition.py < ../ data/small.txt | python3 randomsurfer.py 100000000.27301 0.26569 0.14621 0.24727 0.06782

    $ _

    1.6.3 markov.py

    L markov.py

    1 # Accepts moves (int) as command -line argument and a transition matrix from standard input;2 # computes the probabilities that a random surfer lands on each page (page ranks) after moves3 # matrix -vector multiplications; and writes the page ranks to standard output.45 import stdarray6 import stdio7 import sys89 moves = int(sys.argv [1])

    10 transitionMatrix = stdarray.readFloat2D ()11 n = len(transitionMatrix)12 ranks = stdarray.create1D(n, 0.0)13 ranks [0] = 1.014 for m in range(moves ):15 newRanks = stdarray.create1D(n, 0.0)16 for j in range(n):17 for i in range(n):18 newRanks[j] += ranks[i] * transitionMatrix[i][j]19 ranks = newRanks20 for rank in ranks:21 stdio.writef("%8.5f", rank)22 stdio.writeln ()

    20 / 69

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 transition.py < ../ data/small.txt | python3 markov.py 200.27245 0.26515 0.14669 0.24764 0.06806

    $ python3 transition.py < ../ data/small.txt | python3 markov.py 400.27303 0.26573 0.14618 0.24723 0.06783

    $ _

    2 Procedural Programming

    2.1 Defining Functions

    2.1.1 harmonicredux.py

    L harmonicredux.py

    1 # Accepts n (int) as command -line argument; and writes the nth harmonic number (1 + 1/2 + ... +2 # 1/n) to standard output.34 import stdio5 import sys678 # Entry point.9 def main ():

    10 n = int(sys.argv [1])11 stdio.writeln(_harmonic(n))121314 # Returns the nth harmonic number.15 def _harmonic(n):16 total = 0.017 for i in range(1, n + 1):18 total += 1 / i19 return total202122 if __name__ == ’__main__ ’:23 main()

    & ~/workspace/ipp/programs

    $ python3 harmonicredux.py 102.9289682539682538$ python3 harmonicredux.py 10007.485470860550343$ python3 harmonicredux.py 100009.787606036044348$ _

    2.1.2 couponcollectorredux.py

    L couponcollectorredux.py

    1 # Accepts n (int) as a command -line argument; and writes to standard output the number of coupons2 # you collect before obtaining one of each of n types.34 import stdarray5 import stdio6 import stdrandom7 import sys89

    10 # Entry point.11 def main ():12 n = int(sys.argv [1])13 stdio.writeln(_collect(n))141516 # Collects coupons until getting one of each value in the range 0 to n - 1, and returns the17 # number of coupons collected.18 def _collect(n):19 count = 020 collectedCount = 0

    21 / 69

  • Introduction to Programming in Python

    21 isCollected = stdarray.create1D(n, False)22 while collectedCount < n:23 value = _getCoupon(n)24 count += 125 if not isCollected[value]:26 collectedCount += 127 isCollected[value] = True28 return count293031 # Returns a random coupon between 0 and n - 1.32 def _getCoupon(n):33 return stdrandom.uniformInt (0, n)343536 if __name__ == ’__main__ ’:37 main()

    & ~/workspace/ipp/programs

    $ python3 couponcollectorredux.py 10006276$ python3 couponcollectorredux.py 10007038$ python3 couponcollectorredux.py 100000013401736$ _

    2.1.3 playthattunedeluxe.py

    L playthattunedeluxe.py

    1 # Reads sound samples , each characterized by a pitch and a duration , from standard input; and plays2 # the sound using standard audio.34 import math5 import stdarray6 import stdaudio7 import stdio89

    10 # Entry point.11 def main ():12 while not stdio.isEmpty ():13 pitch = stdio.readInt ()14 duration = stdio.readFloat ()15 stdaudio.playSamples(_createRichNote(pitch , duration ))16 stdaudio.wait()171819 # Returns an array of samples for a note superposed from three notes (at pitch , 2 x pitch ,20 # and 0.5 x pitch) and having the specified duration.21 def _createRichNote(pitch , duration ):22 NOTES_ON_SCALE = 1223 CONCERT_A = 440.024 hz = CONCERT_A * math.pow(2, pitch / NOTES_ON_SCALE)25 mid = _createNote(hz , duration)26 hi = _createNote (2 * hz, duration)27 lo = _createNote(hz / 2, duration)28 hiAndLo = _superpose(hi, lo , 0.5, 0.5)29 return _superpose(mid , hiAndLo , 0.5, 0.5)303132 # Returns an array of samples for a note of specified frequency and duration.33 def _createNote(hz, duration ):34 SPS = 4410035 n = int(SPS * duration)36 note = stdarray.create1D(n + 1, 0.0)37 for i in range(n + 1):38 note[i] = math.sin(2 * math.pi * i * hz / SPS)39 return note404142 # Superposes arrays a and b, using respective weights aWeight and bWeight , and returns the43 # superposed array.44 def _superpose(a, b, aWeight , bWeight ):45 c = stdarray.create1D(len(a), 0.0)46 for i in range(len(a)):

    22 / 69

  • Introduction to Programming in Python

    47 c[i] = a[i] * aWeight + b[i] * bWeight48 return c495051 if __name__ == ’__main__ ’:52 main()

    & ~/workspace/ipp/programs

    $ python3 playthattunedeluxe.py < ../ data/elise.txt$ _

    2.2 Modules and Applications

    2.2.1 gaussiantable.py

    L gaussiantable.py

    1 # Accepts mu (float) and sigma (float) as command -line arguments; and writes to standard output a2 # table of the percentage of students scoring below certain scores on the SAT , assuming the test3 # scores obey a Gaussian distribution with the given mean and standard deviation.45 import gaussian6 import stdio7 import sys89

    10 # Entry point.11 def main ():12 mu = float(sys.argv [1])13 sigma = float(sys.argv [2])14 for score in range (400, 1600 + 1, 100):15 percentile = gaussian.cdf(score , mu, sigma)16 stdio.writef(’%4d %.4f\n’, score , percentile)171819 if __name__ == ’__main__ ’:20 main()

    & ~/workspace/ipp/programs

    $ python3 gaussiantable.py 1019 209400 0.0015500 0.0065600 0.0225700 0.0635800 0.1474900 0.2845

    1000 0.46381100 0.65081200 0.80681300 0.91061400 0.96581500 0.98931600 0.9973$ _

    2.2.2 gaussian.py

    L gaussian.py

    1 # A library of Gaussian functions.23 import math4 import stdio5 import sys678 # Returns the value of the Gaussian probability density function with mean mu and standard9 # deviation sigma at the given x value.

    10 def pdf(x, mu=0.0, sigma =1.0):11 z = (x - mu) / sigma12 return _pdf(z) / sigma1314

    23 / 69

  • Introduction to Programming in Python

    15 # Returns the value of the Gaussian cumulative distribution function with mean mu and standard16 # deviation sigma at the given x value.17 def cdf(x, mu=0.0, sigma =1.0):18 z = float(x - mu) / sigma19 return _cdf(z)202122 # Returns the value of the Gaussian probability density function with mean 0 and standard23 # deviation 1 at the given z value.24 def _pdf(z):25 return math.exp(-z * z / 2) / math.sqrt(2 * math.pi)262728 # Returns the value of the Gaussian cumulative distribution function with mean 0 and standard29 # deviation 1 at the given z value.30 def _cdf(z):31 if z < -8.0:32 return 0.033 if z > +8.0:34 return 1.035 total = 0.036 term = z37 i = 338 while total != total + term:39 total += term40 term *= z * z / i41 i += 242 return 0.5 + total * _pdf(z)434445 # Unit tests the library.46 def _main ():47 x = float(sys.argv [1])48 mu = float(sys.argv [2])49 sigma = float(sys.argv [3])50 stdio.writeln(cdf(x, mu, sigma ))515253 if __name__ == ’__main__ ’:54 _main()

    & ~/workspace/ipp/programs

    $ python3 gaussian.py 820 1019 2090.17050966869132106$ python3 gaussian.py 1500 1019 2090.9893164837383885$ python3 gaussian.py 1500 1025 2310.9801220907365491$ _

    2.2.3 ifs.py

    L ifs.py

    1 # Accepts n (int) as command -line argument , a 1-by-m vector (probabilities) and two m-by -32 # matrices (coefficients for updating x and y, respectively) from standard input; and plots the3 # results as a set of n points using standard output.45 import matrix6 import stdarray7 import stddraw8 import stdrandom9 import sys

    101112 # Entry point.13 def main ():14 n = int(sys.argv [1])15 dist = stdarray.readFloat1D ()16 cx = stdarray.readFloat2D ()17 cy = stdarray.readFloat2D ()18 x, y = 0.0, 0.019 stddraw.setPenRadius (0.0)20 for i in range(n):21 r = stdrandom.discrete(dist)22 col = [x, y, 1]23 x0 = matrix.dot(matrix.row(cx , r), col)

    24 / 69

  • Introduction to Programming in Python

    24 y0 = matrix.dot(matrix.row(cy , r), col)25 x = x026 y = y027 stddraw.point(x, y)28 stddraw.show()293031 if __name__ == ’__main__ ’:32 main()

    & ~/workspace/ipp/programs

    $ python3 ifs.py 100000 < ../ data/sierpinski.txt$ _

    2.2.4 matrix.py

    L matrix.py

    1 # A library of matrix functions.23 import stdarray4 import stdio567 # Returns the ith row of matrix a.8 def row(a, i):9 return a[i]

    101112 # Returns the jth column of matrix a.13 def col(a, j):14 c = []15 for row in a:16 c += [row[j]]17 return c181920 # Returns the sum of the matrices a and b.21 def add(a, b):22 m, n = len(a), len(a[0])23 c = stdarray.create2D(m, n, 0.0)24 for i in range(m):25 for j in range(n):26 c[i][j] = a[i][j] + b[i][j]27 return c282930 # Returns the difference of matrices a and b.31 def subtract(a, b):32 m, n = len(a), len(a[0])33 c = stdarray.create2D(m, n, 0.0)34 for i in range(m):35 for j in range(n):36 c[i][j] = a[i][j] - b[i][j]37 return c

    25 / 69

  • Introduction to Programming in Python

    383940 # Returns the product of matrices a and b.41 def multiply(a, b):42 m, n = len(a), len(b[0])43 c = stdarray.create2D(m, n, 0.0)44 for i in range(m):45 for j in range(n):46 c[i][j] = dot(row(a, i), col(b, j))47 return c484950 # Returns the transpose of matrix a.51 def transpose(a):52 m, n = len(a), len(a[0])53 c = stdarray.create2D(n, m, 0.0)54 for i in range(m):55 for j in range(n):56 c[j][i] = a[i][j]57 return c585960 # Returns the dot product of the 1-by -n matrices a and b.61 def dot(a, b):62 total = 0.063 for x, y in zip(a, b):64 total += x * y65 return total666768 # Unit tests the library.69 def _main ():70 a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]71 b = [[1], [2], [3]]72 stdio.writeln(’a = ’ + str(a))73 stdio.writeln(’b = ’ + str(b))74 stdio.writeln(’row(a, 1) = ’ + str(row(a, 1)))75 stdio.writeln(’col(a, 1) = ’ + str(col(a, 1)))76 stdio.writeln(’add(a, a) = ’ + str(add(a, a)))77 stdio.writeln(’subtract(a, a) = ’ + str(subtract(a, a)))78 stdio.writeln(’multiply(a, b) = ’ + str(multiply(a, b)))79 stdio.writeln(’transpose(b) = ’ + str(transpose(b)))808182 if __name__ == ’__main__ ’:83 _main()

    & ~/workspace/ipp/programs

    $ python3 matrix.pya = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]b = [[1], [2], [3]]row(a, 1) = [4, 5, 6]col(a, 1) = [2, 5, 8]add(a, a) = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]subtract(a, a) = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]multiply(a, b) = [[14.0] , [32.0] , [50.0]]transpose(b) = [[1, 2, 3]]$ _

    2.3 Recursion

    2.3.1 factorial.py

    L factorial.py

    1 # Accepts n (int) as command -line argument; and writes n! to standard output.23 import stdio4 import sys567 # Entry point.8 def main ():9 n = int(sys.argv [1])

    10 stdio.writeln(_factorial(n))11

    26 / 69

  • Introduction to Programming in Python

    1213 # Returns n! computed recursively.14 def _factorial(n):15 if n == 0:16 return 117 return n * _factorial(n - 1)181920 if __name__ == ’__main__ ’:21 main()

    & ~/workspace/ipp/programs

    $ python3 factorial.py 01$ python3 factorial.py 5120$ _

    2.3.2 euclid.py

    L euclid.py

    1 # Accepts p (int) and q (int) as command -line arguments; and writes gcd(p, q) to standard output.23 import stdio4 import sys567 # Entry point.8 def main ():9 p = int(sys.argv [1])

    10 q = int(sys.argv [2])11 stdio.writeln(_gcd(p, q))121314 # Returns the gcd of p and q computed recursively using Euclid ’s algorithm.15 def _gcd(p, q):16 if q == 0:17 return p18 return _gcd(q, p % q)192021 if __name__ == ’__main__ ’:22 main()

    & ~/workspace/ipp/programs

    $ python3 euclid.py 1440 40824$ python3 euclid.py 314159 2718281$ _

    2.3.3 towersofhanoi.py

    L towersofhanoi.py

    1 # Accepts n (int) as command -line argument; and writes to standard output the instructions to move n2 # Towers of Hanoi disks to the left.34 import stdio5 import sys678 # Entry point.9 def main ():

    10 n = int(sys.argv [1])11 _moves(n, True)121314 # Writes to standard output the instructions to move n Towers of Hanoi disks to the left (if15 # parameter left is True) or to the right (if parameter left is False).16 def _moves(n, left):17 if n == 0:

    27 / 69

  • Introduction to Programming in Python

    18 return19 _moves(n - 1, not left)20 if left:21 stdio.writeln(str(n) + ’ left’)22 else:23 stdio.writeln(str(n) + ’ right’)24 _moves(n - 1, not left)252627 if __name__ == ’__main__ ’:28 main()

    & ~/workspace/ipp/programs

    $ python3 towersofhanoi.py 11 left$ python3 towersofhanoi.py 21 right2 left1 right$ python3 towersofhanoi.py 31 left2 right1 left3 left1 left2 right1 left$ python3 towersofhanoi.py 41 right2 left1 right3 right1 right2 left1 right4 left1 right2 left1 right3 right1 right2 left1 right$ _

    2.3.4 htree.py

    L htree.py

    1 # Accepts n (int) as a command -line argument; and draws using standard draw a level n H-tree2 # centered at (0.5, 0.5) with lines of length 0.5.34 import stddraw5 import sys678 # Entry point.9 def main ():

    10 n = int(sys.argv [1])11 stddraw.setPenRadius (0.0)12 _draw(n, 0.5, 0.5, 0.5)13 stddraw.show()141516 # Draws to standard draw a level n H-tree centered at (x, y) with lines of length lineLength.17 def _draw(n, lineLength , x, y):18 if n == 0:19 return20 x0 = x - lineLength / 221 x1 = x + lineLength / 222 y0 = y - lineLength / 223 y1 = y + lineLength / 224 stddraw.line(x0, y, x1, y)25 stddraw.line(x0, y0, x0, y1)26 stddraw.line(x1, y0, x1, y1)27 _draw(n - 1, lineLength / 2, x0, y0)28 _draw(n - 1, lineLength / 2, x0, y1)

    28 / 69

  • Introduction to Programming in Python

    29 _draw(n - 1, lineLength / 2, x1, y0)30 _draw(n - 1, lineLength / 2, x1, y1)313233 if __name__ == ’__main__ ’:34 main()

    & ~/workspace/ipp/programs

    $ python3 htree.py 5$ _

    2.3.5 fibonacci.py

    L fibonacci.py

    1 # Accepts n (int) as command -line argument; and writes the nth Fibonacci number to standard output.23 import stdio4 import sys567 # Entry point.8 def main ():9 n = int(sys.argv [1])

    10 stdio.writeln(_fibonacci(n))111213 # Returns the nth Fibonacci number computed recursively.14 def _fibonacci(n):15 if n == 1 or n == 2:16 return 117 return _fibonacci(n - 1) + _fibonacci(n - 2)181920 if __name__ == ’__main__ ’:21 main()

    & ~/workspace/ipp/programs

    $ python3 fibonacci.py 00$ python3 fibonacci.py 11$ python3 fibonacci.py 21$ python3 fibonacci.py 32$ python3 fibonacci.py 1055$ _

    29 / 69

  • Introduction to Programming in Python

    2.4 Case Study: Fermi’s Paradox (Percolation Problem)

    2.4.1 percolationio.py

    L percolationio.py

    1 # A library of percolation support functions.23 import stdarray4 import stddraw5 import stdrandom6 import sys789 # Returns an n-by-n percolation system with vacancy probability p.

    10 def random(n, p):11 a = stdarray.create2D(n, n, False)12 for i in range(n):13 for j in range(n):14 a[i][j] = stdrandom.bernoulli(p)15 return a161718 # Draws the percolation system a to standard draw. Parameter which indicates whether to display19 # the entries corresponding to True or to False.20 def draw(a, which ):21 n = len(a)22 stddraw.setXscale(-1, n)23 stddraw.setYscale(-1, n)24 for i in range(n):25 for j in range(n):26 if a[i][j] == which:27 stddraw.filledSquare(j, n - i - 1, 0.5)282930 # Unit tests the library.31 def _main ():32 n = int(sys.argv [1])33 p = float(sys.argv [2])34 isOpen = random(n, p)35 draw(isOpen , False)36 stddraw.show()373839 if __name__ == ’__main__ ’:40 _main()

    & ~/workspace/ipp/programs

    $ python3 percolationio.py 10 0.8$ _

    30 / 69

  • Introduction to Programming in Python

    2.4.2 percolation.py

    L percolation.py

    1 # A library of percolation functions.23 import stdio4 import stdarray567 # Computes and returns the full sites of the given percolation system.8 def flow(isOpen ):9 n = len(isOpen)

    10 isFull = stdarray.create2D(n, n, False)11 for j in range(n):12 _flow(isOpen , isFull , 0, j)13 return isFull141516 # Given the full sites of a percolation system , returns True if the system percolates , and False17 # otherwise.18 def percolates(isFull ):19 n = len(isFull)20 for j in range(n):21 if isFull[n - 1][j]:22 return True23 return False242526 # Given the open and full sites of a percolation system , updates the full sites by marking every27 # site of that system that is open and reachable from site (i, j).28 def _flow(isOpen , isFull , i, j):29 n = len(isFull)30 if i < 0 or i >= n or j < 0 or j >= n:31 return32 if not isOpen[i][j] or isFull[i][j]:33 return34 isFull[i][j] = True35 _flow(isOpen , isFull , i + 1, j)36 _flow(isOpen , isFull , i, j + 1)37 _flow(isOpen , isFull , i, j - 1)38 _flow(isOpen , isFull , i - 1, j)394041 # Unit tests the library.42 def _main ():43 isOpen = stdarray.readBool2D ()44 isFull = flow(isOpen)45 stdarray.write2D(isFull)46 stdio.writeln(percolates(isFull ))474849 if __name__ == ’__main__ ’:50 _main()

    & ~/workspace/ipp/programs

    $ python3 percolation.py < ../ data/test5.txt5 50 1 1 0 10 0 1 1 10 0 0 1 10 0 0 0 10 1 1 1 1True$ python3 percolation.py < ../ data/test8.txt8 80 0 1 1 1 0 0 00 0 0 1 1 1 1 10 0 0 0 0 1 1 00 0 0 0 0 1 1 10 0 0 0 0 1 1 00 0 0 0 0 0 1 10 0 0 0 1 1 1 10 0 0 0 0 1 0 0True$ _

    31 / 69

  • Introduction to Programming in Python

    2.4.3 visualize.py

    L visualize.py

    1 # Accepts n (int), p (float), and trials (int) as command -line arguments; generates an n-by -n2 # random percolation system with vacancy probability p; computes the directed percolation flow;3 # and draws the result trials times using standard draw.45 import percolation6 import percolationio7 import stddraw8 import sys9

    1011 # Entry point.12 def main ():13 n = int(sys.argv [1])14 p = float(sys.argv [2])15 trials = int(sys.argv [3])16 for i in range(trials ):17 isOpen = percolationio.random(n, p)18 stddraw.clear()19 stddraw.setPenColor(stddraw.BLACK)20 percolationio.draw(isOpen , False)21 stddraw.setPenColor(stddraw.BLUE)22 isFull = percolation.flow(isOpen)23 percolationio.draw(isFull , True)24 stddraw.show (1000)25 stddraw.show()262728 if __name__ == ’__main__ ’:29 main()

    & ~/workspace/ipp/programs

    $ python3 visualize.py 20 0.65 1$ _

    2.4.4 estimate.py

    L estimate.py

    1 # Accepts n (int), p (float), and trials (int) as command -line arguments; creates trials random2 # n-by-n percolation systems with vacancy probability p; determines the fraction of them that3 # percolates; and writes that fraction to standard output.45 import percolation6 import percolationio7 import stdio8 import sys9

    1011 # Entry point.12 def main ():13 n = int(sys.argv [1])

    32 / 69

  • Introduction to Programming in Python

    14 p = float(sys.argv [2])15 trials = int(sys.argv [3])16 stdio.writeln(evaluate(n, p, trials ))171819 # Generates a random n-by-n percolation system with vacancy probability p and determines if the20 # system percolates. Repeats trials times. Returns an estimate of the empirical percolation21 # probability of such systems.22 def evaluate(n, p, trials ):23 count = 024 for i in range(trials ):25 isOpen = percolationio.random(n, p)26 isFull = percolation.flow(isOpen)27 if percolation.percolates(isFull ):28 count += 129 return count / trials303132 if __name__ == ’__main__ ’:33 main()

    & ~/workspace/ipp/programs

    $ python3 estimate.py 20 0.55 1000.22$ python3 estimate.py 20 0.65 1000.84$ python3 estimate.py 40 0.55 1000.12$ python3 estimate.py 40 0.65 1000.97$ _

    2.4.5 percolationplot.py

    L percolationplot.py

    1 # Accepts n (int) as command -line argument; and draws using standard draw a plot of the percolation2 # probability (experimental observation) against the vacancy probability (control variable ).34 import estimate5 import stddraw6 import sys789 # Entry point.

    10 def main ():11 n = int(sys.argv [1])12 stddraw.setCanvasSize (750, 750)13 stddraw.setXscale (-0.2, 1.2)14 stddraw.setYscale (-0.2, 1.2)15 stddraw.setPenRadius (0.0)16 stddraw.square (0.5, 0.5, 0.52)17 stddraw.setPenColor(stddraw.WHITE)18 stddraw.filledSquare (0.5, 0.5, 0.51)19 stddraw.setPenColor(stddraw.BLACK)20 stddraw.text (0.5, -0.1, ’Vacancy Probability ’)21 stddraw.text (-0.11, 0.5, ’Percolation ’)22 stddraw.text (-0.11, 0.45, ’Probability ’)23 _curve(n, 0.0, 0.0, 1.0, 1.0)24 stddraw.show()252627 # Plots the percolation curve (percolation probability vs vacancy probability) recursively.28 def _curve(n, x0 , y0, x1, y1, trials =10000 , gap =0.01 , error =0.0025):29 xm = (x0 + x1) / 230 ym = (y0 + y1) / 231 fxm = estimate.evaluate(n, xm, trials)32 if x1 - x0 < gap or abs(ym - fxm) < error:33 stddraw.line(x0, y0, x1, y1)34 stddraw.show (0)35 return36 _curve(n, x0 , y0 , xm, fxm)37 stddraw.filledCircle(xm , fxm , 0.005)38 if xm > 0.55 and xm < 0.6:39 xyLabel = ’(’ + str(round(xm, 3)) + ’, ’ + str(round(fxm , 3)) + ’)’40 stddraw.text(xm + 0.1, fxm , xyLabel)41 stddraw.show (0)

    33 / 69

  • Introduction to Programming in Python

    42 _curve(n, xm , fxm , x1, y1)434445 if __name__ == ’__main__ ’:46 main()

    & ~/workspace/ipp/programs

    $ python3 percolationplot.py 20$ _

    3 Object-oriented Programming

    3.1 Using Data Types

    3.1.1 potentialgene.py

    L potentialgene.py

    1 # Accepts dna (str) as command -line argument; and writes to to standard output whether dna2 # corresponds to a potential gene or not.34 import stdio5 import sys678 # Entry point.9 def main ():

    10 dna = sys.argv [1]11 stdio.writeln(_isPotentialGene(dna))121314 # Returns True if dna corresponds to a potential gene , and False otherwise.15 def _isPotentialGene(dna):16 ATG , TAA , TAG , TGA = ’ATG’, ’TAA’, ’TAG’, ’TGA’17 if len(dna) % 3 != 0:18 return False19 if not dna.startswith(ATG):20 return False21 for i in range(len(dna) - 3):22 if i % 3 == 0:23 codon = dna[i:i + 3]24 if codon == TAA or codon == TAG or codon == TGA:25 return False26 return dna.endswith(TAA) or dna.endswith(TAG) or dna.endswith(TGA)272829 if __name__ == ’__main__ ’:30 main()

    34 / 69

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 potentialgene.py ATGCGCCTGCGTCTGTACTAGTrue$ python3 potentialgene.py ATGCGCTGCGTCTGTACTAGFalse$ _

    3.1.2 alberssquares.py

    L alberssquares.py

    1 # Accepts r1 (int), g1 (int), b1 (int), r2 (int), g2 (int), and b2 (int) as command -line2 # arguments; and draws using standard draw Albers ’ squares with colors (r1, g1, b1) and (r2, g2,3 # b2).45 from color import Color6 import stddraw7 import sys89

    10 # Entry point.11 def main ():12 r1 = int(sys.argv [1])13 g1 = int(sys.argv [2])14 b1 = int(sys.argv [3])15 r2 = int(sys.argv [4])16 g2 = int(sys.argv [5])17 b2 = int(sys.argv [6])18 c1 = Color(r1, g1, b1)19 c2 = Color(r2, g2, b2)20 stddraw.setCanvasSize (512, 256)21 stddraw.setYscale (0.25, 0.75)22 stddraw.setPenColor(c1)23 stddraw.filledSquare (0.25 , 0.5, 0.2)24 stddraw.setPenColor(c2)25 stddraw.filledSquare (0.25 , 0.5, 0.1)26 stddraw.setPenColor(c2)27 stddraw.filledSquare (0.75 , 0.5, 0.2)28 stddraw.setPenColor(c1)29 stddraw.filledSquare (0.75 , 0.5, 0.1)30 stddraw.show()313233 if __name__ == ’__main__ ’:34 main()

    & ~/workspace/ipp/programs

    $ python3 alberssquares.py 0 174 239 147 149 252$ _

    3.1.3 luminance.py

    L luminance.py

    1 # A library of color -related functions.23 from color import Color4 import stdio5 import sys67

    35 / 69

  • Introduction to Programming in Python

    8 # Returns the luminance of the Color c.9 def luminance(c):

    10 r = c.getRed ()11 g = c.getGreen ()12 b = c.getBlue ()13 if r == g and r == b:14 return r15 return 0.299 * r + 0.587 * g + 0.114 * b161718 # Returns the grayscale equivalent of Color c.19 def toGray(c):20 y = int(round(luminance(c)))21 gray = Color(y, y, y)22 return gray232425 # Returns True if Color c1 is compatible with Color c2, and False otherwise.26 def areCompatible(c1, c2):27 return abs(luminance(c1) - luminance(c2)) >= 128.0282930 # Unit tests the library.31 def _main ():32 r1 = int(sys.argv [1])33 g1 = int(sys.argv [2])34 b1 = int(sys.argv [3])35 r2 = int(sys.argv [4])36 g2 = int(sys.argv [5])37 b2 = int(sys.argv [6])38 c1 = Color(r1, g1, b1)39 c2 = Color(r2, g2, b2)40 stdio.writeln(str(c1) + ’ compatible with ’ + str(c2) + ’? ’ + str(areCompatible(c1, c2)))414243 if __name__ == ’__main__ ’:44 _main()

    & ~/workspace/ipp/programs

    $ python3 luminance.py 0 0 0 0 0 255(0, 0, 0) compatible with (0, 0, 255)? False$ _

    3.1.4 grayscale.py

    L grayscale.py

    1 # Accepts filename (str) as command -line argument; reads an image from a file with that name; and2 # renders a gray scale version of that image.34 from picture import Picture5 import luminance6 import stddraw7 import sys89

    10 # Entry point.11 def main ():12 filename = sys.argv [1]13 picture = Picture(filename)14 for col in range(picture.width ()):15 for row in range(picture.height ()):16 pixel = picture.get(col , row)17 gray = luminance.toGray(pixel)18 picture.set(col , row , gray)19 stddraw.setCanvasSize(picture.width(), picture.height ())20 stddraw.picture(picture)21 stddraw.show()222324 if __name__ == ’__main__ ’:25 main()

    & ~/workspace/ipp/programs

    $ python3 grayscale.py ../ data/mandrill.jpg$ _

    36 / 69

  • Introduction to Programming in Python

    3.1.5 fade.py

    L fade.py

    1 # Accepts sourceFile (str), targetFile (str), and n (int) as command -line arguments; reads images2 # from sourceFile and targetFile; over the course of n frames , gradually replaces the image from3 # sourceFile with the image from targetFile; and displays each intermediate image using standard4 # draw.56 from color import Color7 from picture import Picture8 import stddraw9 import sys

    101112 # Entry point.13 def main ():14 sourceFile = sys.argv [1]15 targetFile = sys.argv [2]16 n = int(sys.argv [3])17 source = Picture(sourceFile)18 target = Picture(targetFile)19 width = source.width()20 height = source.height ()21 stddraw.setCanvasSize(width , height)22 picture = Picture(width , height)23 for i in range(n + 1):24 for col in range(width):25 for row in range(height ):26 c0 = source.get(col , row)27 cn = target.get(col , row)28 alpha = i / n29 c = _blend(c0, cn , alpha)30 picture.set(col , row , c)31 stddraw.picture(picture)32 stddraw.show (1)33 stddraw.show()343536 # Returns a new Color object which blends Color objects c1 and c2 using alpha as the blending37 # factor.38 def _blend(c1 , c2, alpha):39 r = (1 - alpha) * c1.getRed () + alpha * c2.getRed ()40 g = (1 - alpha) * c1.getGreen () + alpha * c2.getGreen ()41 b = (1 - alpha) * c1.getBlue () + alpha * c2.getBlue ()42 return Color(int(r), int(g), int(b))434445 if __name__ == ’__main__ ’:46 main()

    & ~/workspace/ipp/programs

    $ python3 fade.py ../ data/mandrill.jpg ../ data/darwin.jpg 5$ _

    37 / 69

  • Introduction to Programming in Python

    3.1.6 cat.py

    L cat.py

    1 # Accepts sys.argv [1:n-2] files or web pages as command -line arguments; and copies them to the2 # file whose name is accepted as command -line argument sys.argv[n-1].34 from instream import InStream5 from outstream import OutStream6 import sys789 # Entry point.

    10 def main ():11 n = len(sys.argv)12 outStream = OutStream(sys.argv[n - 1])13 for i in range(1, n - 1):14 inStream = InStream(sys.argv[i])15 s = inStream.readAll ()16 outStream.write(s)171819 if __name__ == ’__main__ ’:20 main()

    & ~/workspace/ipp/programs

    $ cat ../ data/in1.txtThis is$ cat ../ data/in2.txta tinytest.$ python3 cat.py ../ data/in1.txt ../ data/in2.txt out.txt$ cat out.txtThis isa tinytest.$ _

    3.1.7 split.py

    L split.py

    1 # Accepts filename (str) and n (int) as command -line arguments; and splits the file whose name is2 # filename.csv , by field , into n files named filename1.txt , filename2.txt , etc.34 from instream import InStream5 from outstream import OutStream6 import stdarray7 import sys89

    10 # Entry point.11 def main ():12 filename = sys.argv [1]13 n = int(sys.argv [2])14 outStreams = stdarray.create1D(n, None)15 for i in range(n):16 outStreams[i] = OutStream(filename + str(i + 1) + ’.txt’)17 inStream = InStream(filename + ’.csv’)18 while inStream.hasNextLine ():19 line = inStream.readLine ()20 fields = line.split(’,’)

    38 / 69

  • Introduction to Programming in Python

    21 for i in range(n):22 outStreams[i]. writeln(fields[i])232425 if __name__ == ’__main__ ’:26 main()

    & ~/workspace/ipp/programs

    $ head -5 ../ data/ip.csvwww.princeton.edu ,128.112.128.15www.cs.princeton.edu ,128.112.136.35www.math.princeton.edu ,128.112.18.11www.cs.harvard.edu ,140.247.50.127www.harvard.edu ,128.103.60.24$ python3 split.py ../ data/ip 2$ head -5 ../ data/ip1.txtwww.princeton.eduwww.cs.princeton.eduwww.math.princeton.eduwww.cs.harvard.eduwww.harvard.edu$ head -5 ../ data/ip2.txt128.112.128.15128.112.136.35128.112.18.11140.247.50.127128.103.60.24$ _

    3.2 Creating Data Types

    3.2.1 timeops.py

    L timeops.py

    1 # Accepts n (int) as command -line argument; computes the sum 1^0.5 + 2^0.5 + ... + n^0.5 using2 # math.sqrt(x) and math.pow(x) to calculate the square root of x; and writes to standard output a3 # comparison of the performance characteristics of the two functions.45 from stopwatch import Stopwatch6 import math7 import stdio8 import sys9

    1011 # Entry point.12 def main ():13 n = int(sys.argv [1])14 watch1 = Stopwatch ()15 total = 0.016 for i in range(1, n + 1):17 total += math.sqrt(i)18 time1 = watch1.elapsedTime ()19 watch2 = Stopwatch ()20 total = 0.021 for i in range(1, n + 1):22 total += math.pow(i, 0.5)23 time2 = watch2.elapsedTime ()24 stdio.writef(’math.sqrt() is %.2f times faster than math.pow()\n’, time2 / time1)252627 if __name__ == ’__main__ ’:28 main()

    & ~/workspace/ipp/programs

    $ python3 timeops.py 10000000math.sqrt() is 2.05 times faster than math.pow()$ _

    39 / 69

  • Introduction to Programming in Python

    3.2.2 stopwatch.py

    L stopwatch.py

    1 # An immutable data type to measure the running (wall clock) time of a program.23 import stdio4 import sys5 import time678 class Stopwatch:9 # Constructs a new stopwatch.

    10 def __init__(self):11 self._creationTime = time.time() # creation time of stopwatch1213 # Returns the elapsed time (in seconds) since creation.14 def elapsedTime(self):15 return time.time() - self._creationTime1617 # Returns a string representation of this stopwatch.18 def __str__(self):19 return str(self.elapsedTime ())202122 # Unit tests the data type.23 def _main ():24 n = int(sys.argv [1])25 watch = Stopwatch ()26 primes = 027 for i in range(2, n + 1):28 j = 229 while j i / j:34 primes += 135 time = watch.elapsedTime ()36 stdio.writef(’pi(%d) = %d computed in %.5f seconds\n’, n, primes , time)373839 if __name__ == ’__main__ ’:40 _main()

    & ~/workspace/ipp/programs

    $ python3 stopwatch.py 1000000pi (1000000) = 78498 computed in 6.43457 seconds$ _

    3.2.3 bernoulli.py

    L bernoulli.py

    1 # Accepts n (int), p (float), and trials (int) as command -line arguments; performs trials2 # experiments , each of which counts the number of heads found when a coin with bias p is3 # flipped n times; and draws the results using standard draw.45 from histogram import Histogram6 import stddraw7 import stdrandom8 import sys9

    1011 # Entry point.12 def main ():13 n = int(sys.argv [1])14 p = float(sys.argv [2])15 trials = int(sys.argv [3])16 histogram = Histogram(n + 1)17 for t in range(trials ):18 heads = stdrandom.binomial(n, p)19 histogram.addDataPoint(heads)20 stddraw.setCanvasSize (500, 200)21 histogram.draw()22 stddraw.show()

    40 / 69

  • Introduction to Programming in Python

    232425 if __name__ == ’__main__ ’:26 main()

    & ~/workspace/ipp/programs

    $ python3 bernoulli.py 100 0.5 10000$ _

    3.2.4 histogram.py

    L histogram.py

    1 # A data type that represents histograms of the frequency of occurrence of values in [0, n).23 import stdarray4 import stddraw5 import stdrandom6 import stdstats7 import sys89

    10 class Histogram:11 # Constructs a histogram to store frequency of occurrence of values [0, n).12 def __init__(self , n):13 self._freq = stdarray.create1D(n, 0) # array of frequencies1415 # Adds one occurrence of the value i.16 def addDataPoint(self , i):17 self._freq[i] += 11819 # Draws this histogram to standard draw.20 def draw(self):21 stddraw.setYscale(-1, max(self._freq) + 1)22 stdstats.plotBars(self._freq)2324 # Returns a string representation of this histogram.25 def __str__(self):26 return str(self._freq)272829 # Unit tests the data type.30 def _main ():31 trials = int(sys.argv [1])32 histogram = Histogram (6)33 for t in range(trials ):34 roll = stdrandom.uniformInt (0, 6)35 histogram.addDataPoint(roll)36 stddraw.setCanvasSize (500, 200)37 histogram.draw()38 stddraw.show()394041 if __name__ == ’__main__ ’:42 _main()

    & ~/workspace/ipp/programs

    $ python3 histogram.py 1000$ _

    41 / 69

  • Introduction to Programming in Python

    3.2.5 drunks.py

    L drunks.py

    1 # Accepts n (int), steps (int), and stepSize (float) as command -line arguments; creates n Turtle2 # objects; and has the turtles take steps random steps , each of size stepSize.34 from turtle import Turtle5 import stdarray6 import stddraw7 import stdrandom8 import sys9

    1011 # Entry point.12 def main ():13 n = int(sys.argv [1])14 steps = int(sys.argv [2])15 stepSize = float(sys.argv [3])16 turtles = stdarray.create1D(n, None)17 for i in range(n):18 x = stdrandom.uniformFloat (0.0, 1.0)19 y = stdrandom.uniformFloat (0.0, 1.0)20 theta = stdrandom.uniformFloat (0.0, 360.0)21 turtles[i] = Turtle(x, y, theta)22 stddraw.setPenRadius (0.0)23 for i in range(steps ):24 for turtle in turtles:25 theta = stdrandom.uniformFloat (0.0, 360.0)26 turtle.turnLeft(theta)27 turtle.goForward(stepSize)28 stddraw.show (0.0)29 stddraw.show()303132 if __name__ == ’__main__ ’:33 main()

    & ~/workspace/ipp/programs

    $ python3 drunks.py 20 1000 0.01$ _

    42 / 69

  • Introduction to Programming in Python

    3.2.6 turtle.py

    L turtle.py

    1 # A data type for turtle graphics using standard draw.23 import math4 import stddraw5 import sys678 class Turtle:9 # Constructs a turtle given its coordinates and angle.

    10 def __init__(self , x, y, theta):11 self._x = x # x-coordinate of turtle12 self._y = y # y-coordinate of turtle13 self._theta = theta # ccw angle (in degrees) of turtle1415 # Rotates this turtle by theta in ccw direction.16 def turnLeft(self , theta):17 self._theta += theta1819 # Moves this turtle forward by given amount , with the pen down.20 def goForward(self , stepSize ):21 xOld = self._x22 yOld = self._y23 self._x += stepSize * math.cos(math.radians(self._theta ))24 self._y += stepSize * math.sin(math.radians(self._theta ))25 stddraw.line(xOld , yOld , self._x, self._y)2627 # Returns a string representation of this turtle.28 def __str__(self):29 return ’(’ + str(self._x) + ’, ’ + str(self._y) + ’, ’ + str(self._theta) + ’)’303132 # Unit tests the data type.33 def _main ():34 n = int(sys.argv [1])35 turtle = Turtle (0.5, 0.0, 180.0 / n)36 stepSize = math.sin(math.radians (180.0 / n))37 stddraw.setPenRadius (0.0)38 for i in range(n):39 turtle.goForward(stepSize)40 turtle.turnLeft (360.0 / n)41 stddraw.show()424344 if __name__ == ’__main__ ’:45 _main()

    & ~/workspace/ipp/programs

    $ python3 turtle.py 10$ _

    43 / 69

  • Introduction to Programming in Python

    3.3 Designing Data Types

    3.3.1 complex.py

    L complex.py

    1 # An immutable data type to represent a complex number using cartesian coordinates.23 import math4 import stdio567 class Complex:8 # Constructs a complex number given its cartesian coordinates.9 def __init__(self , re=0.0, im =0.0):

    10 self._re = re # the real part11 self._im = im # the imaginary part1213 # Returns the real part of this complex number.14 def re(self):15 return self._re1617 # Returns the imaginary part of this complex number.18 def im(self):19 return self._im2021 # Returns the conjugate of this complex number.22 def conjugate(self):23 return Complex(self._re , -self._im)2425 # Returns the sum of this and the other complex number.26 def __add__(self , other):27 re = self._re + other._re28 im = self._im + other._im29 return Complex(re , im)3031 # Returns the product of this and the other complex number.32 def __mul__(self , other):33 re = self._re * other._re - self._im * other._im34 im = self._re * other._im + self._im * other._re35 return Complex(re , im)3637 # Returns the magnitude of this complex number.38 def __abs__(self):39 return math.sqrt(self._re * self._re + self._im * self._im)4041 # Returns True if this and other denote the same complex number , and False otherwise.42 def __eq__(self , other ):43 return self._re == other._re and self._im == other._im4445 # Returns a string representation of this complex number.46 def __str__(self):47 SUFFIX = ’i’48 if self._im == 0:49 return str(self._re)50 elif self._re == 0:51 return str(self._im) + SUFFIX52 elif self._im < 0:53 return str(self._re) + ’ - ’ + str(-self._im) + SUFFIX54 else:55 return str(self._re) + ’ + ’ + str(self._im) + SUFFIX565758 # Unit tests the data type.59 def _main ():60 a = Complex (5.0, -6.0)61 b = Complex (3.0, 4.0)62 stdio.writeln("a = " + str(a))63 stdio.writeln("b = " + str(b))64 stdio.writeln("conj(a) = " + str((a.conjugate ())))65 stdio.writeln("a + b = " + str(a + b))66 stdio.writeln("a * b = " + str(a * b))67 stdio.writeln("|b| = " + str(abs(b)))686970 if __name__ == ’__main__ ’:71 _main()

    44 / 69

  • Introduction to Programming in Python

    & ~/workspace/ipp/programs

    $ python3 complex.pya = 5.0 - 6.0ib = 3.0 + 4.0iconj(a) = 5.0 + 6.0ia + b = 8.0 - 2.0ia * b = 39.0 + 2.0i|b| = 5.0$ _

    3.3.2 mandelbrot.py

    L mandelbrot.py

    1 # Accepts xc (float), yc (float), and size (float) as command -line arguments; and draws using2 # standard draw the size -by -size region of the Mandelbrot set , centered at (xc, yc).34 from color import Color5 from complex import Complex6 from picture import Picture7 import stddraw8 import sys9

    1011 # Entry point.12 def main ():13 xc = float(sys.argv [1])14 yc = float(sys.argv [2])15 size = float(sys.argv [3])16 N = 51217 ITERATIONS = 25518 picture = Picture(N, N)19 for col in range(N):20 for row in range(N):21 x0 = xc - size / 2 + size * col / N22 y0 = yc - size / 2 + size * row / N23 z0 = Complex(x0 , y0)24 gray = ITERATIONS - _mandel(z0 , ITERATIONS)25 color = Color(gray , gray , gray)26 picture.set(col , N - 1 - row , color)27 stddraw.setCanvasSize(N, N)28 stddraw.picture(picture)29 stddraw.show()303132 # Returns the number of iterations to check if z0 is in the Mandelbrot set.33 def _mandel(z0, iterations ):34 z = z035 for i in range(iterations ):36 if abs(z) > 2.0:37 return i38 z = z * z + z039 return iterations404142 if __name__ == ’__main__ ’:43 main()

    & ~/workspace/ipp/programs

    $ python3 mandelbrot.py -0.5 0 2$ _

    45 / 69

  • Introduction to Programming in Python

    3.3.3 vector.py

    L vector.py

    1 # An immutable data type to represent an n-dimensional vector.23 import math4 import stdarray5 import stdio678 class Vector:9 # Constructs a vector given its components.

    10 def __init__(self , a):11 self._n = len(a) # dimension of vector12 self._coords = a[:] # defensive copy of array of components1314 # Returns the ith component of this vector.15 def __getitem__(self , i):16 return self._coords[i]1718 # Returns the sum of this and the other vector.19 def __add__(self , other):20 result = stdarray.create1D(self._n , 0)21 for i in range(self._n):22 result[i] = self._coords[i] + other._coords[i]23 return Vector(result)2425 # Returns the difference of this and the other vector.26 def __sub__(self , other):27 result = stdarray.create1D(self._n , 0)28 for i in range(self._n):29 result[i] = self._coords[i] - other._coords[i]30 return Vector(result)3132 # Returns the dot product of this and the other vector.33 def dot(self , other):34 result = 035 for i in range(self._n):36 result += self._coords[i] * other._coords[i]37 return result3839 # Returns a scaled (by factor alpha) copy of this vector.40 def scale(self , alpha ):41 result = stdarray.create1D(self._n , 0)42 for i in range(self._n):43 result[i] = alpha * self._coords[i]44 return Vector(result)4546 # Returns a unit vector in the direction of this vector.47 def direction(self):48 return self.scale (1.0 / abs(self))4950 # Returns the magnitude of this vector.51 def __abs__(self):52 return math.sqrt(self.dot(self))5354 # Returns the dimension of this vector.

    46 / 69

  • Introduction to Programming in Python

    55 def dimension(self):56 return self._n5758 # Returns a string representation of this vector.59 def __str__(self):60 return str(self._coords)616263 # Unit tests the data type.64 def _main ():65 xCoords = [1.0, 2.0, 3.0, 4.0]66 yCoords = [5.0, 2.0, 4.0, 1.0]67 x = Vector(xCoords)68 y = Vector(yCoords)69 stdio.writeln(’x = ’ + str(x))70 stdio.writeln(’y = ’ + str(y))71 stdio.writeln(’x + y = ’ + str(x + y))72 stdio.writeln(’x - y = ’ + str(x - y))73 stdio.writeln(’x dot y = ’ + str(x.dot(y)))74 stdio.writeln(’10x = ’ + str(x.scale (10.0)))75 stdio.writeln(’xhat = ’ + str(x.direction ()))76 stdio.writeln(’|x| = ’ + str(abs(x)))77 stdio.writeln(’ydim = ’ + str(y.dimension ()))787980 if __name__ == ’__main__ ’:81 _main()

    & ~/workspace/ipp/programs

    $ python3 vector.pyx = [1.0, 2.0, 3.0, 4.0]y = [5.0, 2.0, 4.0, 1.0]x + y = [6.0, 4.0, 7.0, 5.0]x - y = [-4.0, 0.0, -1.0, 3.0]x dot y = 25.010x = [10.0, 20.0, 30.0, 40.0]xhat = [0.18257418583505536 , 0.3651483716701107 , 0.5477225575051661 , 0.7302967433402214]|x| = 5.477225575051661ydim = 4$ _

    3.3.4 sketch.py

    L sketch.py

    1 # An immutable data type that represents a profile of a string , as a d-dimensional unit vector.23 from vector import Vector4 import stdarray5 import stdio6 import sys789 class Sketch:

    10 # Constructs a new sketch which is a profile of text , as a d-dimensional unit vector.11 # Component i of the vector indicates how many k-grams in the text hash to i.12 def __init__(self , text , k, d):13 freq = stdarray.create1D(d, 0)14 for i in range(len(text) - k + 1):15 kgram = text[i:i + k]16 h = hash(kgram)17 freq[abs(h % d)] += 118 vector = Vector(freq)19 self._sketch = vector.direction () # string profile as a d-dimensional unit vector2021 # Returns the similarity measure between this and the other sketch , as a number between 0 and 1.22 # The value 0 indicates that the sketches are dissimilar , and 1 indicates that they are similar.23 def similarTo(self , other):24 return self._sketch.dot(other._sketch)2526 # Returns a string representation of this sketch.27 def __str__(self):28 return str(self._sketch)293031 # Unit tests the data type.32 def _main ():

    47 / 69

  • Introduction to Programming in Python

    33 k = int(sys.argv [1])34 d = int(sys.argv [2])35 text = stdio.readAll ()36 sketch = Sketch(text , k, d)37 stdio.writeln(sketch)383940 if __name__ == ’__main__ ’:41 _main()

    & ~/workspace/ipp/programs

    $ python3 sketch.py 2 16 < ../ data/genome20.txt[0.35603449745815596 , 0.0, 0.0, 0.4747126632775413 , 0.11867816581938533 , 0.23735633163877065 , 0.0, 0.0, 0.0,0.4747126632775413 , 0.0, 0.0, 0.5933908290969266 , 0.0, 0.0, 0.0]$ _

    3.3.5 comparedocuments.py

    L comparedocuments.py

    1 # Accepts k (int), d (int), and path (str) as command -line arguments; reads a document list2 # from standard input; computes d-dimensional profiles based on k-gram frequencies for all those3 # documents under the path directory; and writes to standard output a matrix of similarity measures4 # between all pairs of documents.56 from instream import InStream7 from sketch import Sketch8 import stdarray9 import stdio

    10 import sys111213 # Entry point.14 def main ():15 k = int(sys.argv [1])16 d = int(sys.argv [2])17 path = sys.argv [3]18 filenames = stdio.readAllStrings ()19 n = len(filenames)20 sketches = stdarray.create1D(n, None)21 for i in range(n):22 inStream = InStream(path + ’/’ + filenames[i])23 text = inStream.readAll ()24 sketches[i] = Sketch(text , k, d)25 stdio.write(’ ’)26 for filename in filenames:27 stdio.writef(’%8.4s’, filename)28 stdio.writeln ()29 for i in range(n):30 stdio.writef(’%.4s’, filenames[i])31 for j in range(n):32 stdio.writef(’%8.2f’, sketches[i]. similarTo(sketches[j]))33 stdio.writeln ()343536 if __name__ == ’__main__ ’:37 main()

    & ~/workspace/ipp/programs

    $ python3 comparedocuments.py 5 10000 ../ data < ../ data/documents.txtcons toms huck tale prej actg djia

    cons 1.00 0.66 0.60 0.67 0.64 0.11 0.18toms 0.66 1.00 0.93 0.92 0.88 0.15 0.23huck 0.60 0.93 1.00 0.84 0.81 0.13 0.21tale 0.67 0.92 0.84 1.00 0.87 0.14 0.21prej 0.64 0.88 0.81 0.87 1.00 0.15 0.24actg 0.11 0.15 0.13 0.14 0.15 1.00 0.12djia 0.18 0.23 0.21 0.21 0.24 0.12 1.00$ _

    48 / 69

  • Introduction to Programming in Python

    3.3.6 counter.py

    L counter.py

    1 # A comparable data type to represent a counter.23 import stdarray4 import stdio5 import stdrandom6 import sys789 class Counter:

    10 # Initializes a new counter with the given id.11 def __init__(self , id):12 self._id = id # counter name13 self._count = 0 # current value1415 # Increments this counter by 1.16 def increment(self):17 self._count += 11819 # Returns the current value of this counter.20 def tally(self):21 return self._count2223 # Resets this counter to zero.24 def reset(self):25 self._count = 02627 # Returns True if this counter is less than the other counter by count , and False otherwise.28 def __lt__(self , other ):29 return self._count < other._count3031 # Returns True if this and the other counter have the same count , and False otherwise.32 def __eq__(self , other ):33 return self._count == other._count3435 # Returns a string representation of this counter.36 def __str__(self):37 return str(self._count) + ’ ’ + self._id383940 # Unit tests the data type.41 def _main ():42 n = int(sys.argv [1])43 trials = int(sys.argv [2])44 counters = stdarray.create1D(n, None)45 for i in range(n):46 counters[i] = Counter(’counter ’ + str(i))47 for i in range(trials ):48 counters[stdrandom.uniformInt (0, n)]. increment ()49 for counter in sorted(counters ):50 stdio.writeln(counter)515253 if __name__ == ’__main__ ’:54 _main()

    & ~/workspace/ipp/programs

    $ python3 counter.py 6 100001620 counter 01629 counter 31653 counter 21686 counter 11686 counter 41726 counter 5$ _

    49 / 69

  • Introduction to Programming in Python

    3.3.7 country.py

    L country.py

    1 # A comparable data type that represents a country by its name , capital , and population.23 import stdarray4 import stdio567 class Country:8 # Constructs a country given its name , capital , and population.9 def __init__(self , name , capital , population ):

    10 self._name = name # name11 self._capital = capital # capital city12 self._population = population # population1314 # Returns True if this country is less than the other country by name , and False otherwise.15 def __lt__(self , other ):16 return self._name < other._name1718 # Returns True if this and the other country have the same name , and False otherwise.19 def __eq__(self , other ):20 return self._name == other._name2122 # Returns a string representation of this country.23 def __str__(self):24 return self._name + ’ (’ + self._capital + ’): ’ + str(self._population)252627 # Unit tests the data type.28 def _main ():29 countries = stdarray.create1D(5, None)30 countries [0] = Country(’United States ’, ’Washington , D.C.’, 329334246)31 countries [1] = Country(’Pakistan ’, ’Islamabad ’, 218719520)32 countries [2] = Country(’India’, ’New Delhi ’, 1358989650)33 countries [3] = Country(’China’, ’Beijing ’, 1401463880)34 countries [4] = Country(’Indonesia ’, ’Jakarta ’, 266911900)35 stdio.writeln(’Unsorted:’)36 for country in countries:37 stdio.writeln(country)38 stdio.writeln ()39 stdio.writeln(’Sorted by name:’)40 for country in sorted(countries ):41 stdio.writeln(country)42 stdio.writeln ()43 stdio.writeln(’Sorted by capital:’)44 for country in sorted(countries , key=lambda country: country._capital ):45 stdio.writeln(country)46 stdio.writeln ()47 stdio.writeln(’Sorted by population:’)48 for country in sorted(countries , key=lambda country: country._population ):49 stdio.writeln(country)50 stdio.writeln ()51 stdio.writeln(’Reverse sorted by population:’)52 for country in sorted(countries , key=lambda country: country._population , reverse=True):53 stdio.writeln(country)545556 if __name__ == ’__main__ ’:57 _main()

    & ~/workspace/ipp/programs

    $ python3 country.pyUnsorted:United States (Washington , D.C.): 329334246Pakistan (Islamabad ): 218719520India (New Delhi): 1358989650China (Beijing ): 1401463880Indonesia (Jakarta ): 266911900

    Sorted by name:China (Beijing ): 1401463880India (New Delhi): 1358989650Indonesia (Jakarta ): 266911900Pakistan (Islamabad ): 218719520United States (Washington , D.C.): 329334246

    Sorted by capital:

    50 / 69

  • Introduction to Programming in Python

    China (Beijing ): 1401463880Pakistan (Islamabad ): 218719520Indonesia (Jakarta ): 266911900India (New Delhi): 1358989650United States (Washington , D.C.): 329334246

    Sorted by population:Pakistan (Islamabad ): 218719520Indonesia (Jakarta ): 266911900United States (Washington , D.C.): 329334246India (New Delhi): 1358989650China (Beijing ): 1401463880

    Reverse sorted by population:China (Beijing ): 1401463880India (New Delhi): 1358989650United States (Washington , D.C.): 329334246Indonesia (Jakarta ): 266911900Pakistan (Islamabad ): 218719520$ _

    3.3.8 fibonaccisequence.py

    L fibonaccisequence.py

    1 # An iterable data type to iterate over the first n numbers from the Fibonacci sequence.23 import stdio4 import sys567 class FibonacciSequence:8 # Constructs a FibonacciSequence object given the length of the sequence.9 def __init__(self , n):

    10 self._n = n # length of the sequence1112 # Returns an iterator that iterates over the numbers in the sequence.13 def __iter__(self):14 self._a = -1 # previous number in the sequence15 self._b = 1 # current number in the sequence16 self._count = 0 # count of numbers iterated so far17 return self1819 # Returns the next number in the sequence if there is one , and raises StopIteation20 # otherwise.21 def __next__(self):22 self._count += 123 if self._count > self._n:24 raise StopIteration ()25 temp = self._a26 self._a = self._b27 self._b += temp28 return self._b293031 # Unit tests th


Recommended