Docsity

50 Examples Documentation, Study notes of English

Partial preview of the text

Download 50 Examples Documentation and more Study notes English in PDF only on Docsity!

50 Examples Documentation

Release 1.

A.M. Kuchling

Apr 13, 2017

ii

Contents:

  • 1 Introduction
  • 2 Convert Fahrenheit to Celsius
  • 3 Background: Algorithms
  • 4 Background: Measuring Complexity
  • 5 Simulating The Monty Hall Problem
  • 6 Background: Drawing Graphics
  • 7 Simulating Planetary Orbits
  • 8 Problem: Simulating the Game of Life
  • 9 Reference Card: Turtle Graphics
  • 10 Indices and tables
  • 50 Examples Documentation, Release 1.
  • Release 1.
  • Date Apr 13,
  • Contents

CHAPTER 1

Introduction

Welcome to “50 Examples for Teaching Python”.

My goal was to collect interesting short examples of Python programs, examples that tackle a real-world problem and exercise various features of the Python language. I envision this collection as being useful to teachers of Python who want novel examples that will interest their students, and possibly to teachers of mathematics or science who want to apply Python programming to make their subject more concrete and interactive.

Readers may also enjoy dipping into the book to learn about a particular algorithm or technique, and can use the references to pursue further reading on topics that especially interest them.

Python version

All of the examples in the book were written using Python 3, and tested using Python 3.2.1. You can download a copy of Python 3 from ; use the latest version available.

This book is not a Python tutorial and doesn’t try to introduce features of the language, so readers should either be familiar with Python or have a tutorial available. Classes and modules are used right from the beginning, for example; the early programs do not use a subset of the language that’s later expanded by the introduction of more sophisticated features such as classes.

License

The English text of this work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3. Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

This license forbids publishing and selling copies of the book, but you are free to print copies for your own private or educational use. For example, it’s OK to print out a section as a handout for a class, or to include sections in documents that you write and make available under the same Creative Commons license.

50 Examples Documentation, Release 1.

If you wish to sell copies of the book or include partial sections of the text in your own works made available under a different license, please contact the author to request permission.

The software programs are released under the MIT license, and you are free to use or modify them in any way you like, including for commercial purposes or in other documentation projects.

The original source text and example code is available at https://github.com/akuchling/50-examples, and is formatted using the Sphinx documentation tool (http://sphinx.pocoo.org).

Please send questions, suggestions, and comments to the e-mail address below.

A.M. Kuchling

[email protected]

4 Chapter 1. Introduction

50 Examples Documentation, Release 1.

7 8 Converts a Fahrenheit temperature represented as a string 9 to a Celsius temperature. 10 """ 11 fahrenheit = float(S) 12 celsius = (fahrenheit - 32) * 5 / 9 13 return celsius 14 15 def main(): 16 # If no arguments were given, print a helpful message 17 if len(sys.argv) == 1: 18 print('Usage: {} temp1 temp2 ...'.format(sys.argv[0])) 19 sys.exit(0) 20 21 # Loop over the arguments 22 for arg in sys.argv[1:]: 23 try : 24 celsius = convert_f2c(arg) 25 except ValueError: 26 print("{!r} is not a numeric value".format(arg), 27 file=sys.stderr) 28 else : 29 print('{} \N{DEGREE SIGN} F = {:g} \N{DEGREE SIGN} C'.format( 30 arg, round(celsius, 0))) 31 32 if name == 'main': 33 main()

Code Discussion

Here we will dive further into the code, discussing particularly interesting sections of code, programming techniques, or larger issues. The conversion to Celsius done by the convert_f2c() function is a straightforward calculation. An input string is converted to a floating-point value. If there’s a problem, the resulting ValueError exception is not handled here but instead is left for the caller to catch. Notice that the main() function tries to print a helpful message when no command-line arguments are provided, and it also catches the ValueError. For pedagogical programs like this, I will try to ensure the error handling is helpful to a user experimenting with the script.

Lessons Learned

Finally, does this program demonstrate any interesting themes about Python, about programming in general, or about its subject matter? For this celsius example, I’ll discuss Python’s string format() method and the mini-language it uses, since it will be used throughout our example programs. The strings used with the format() method will contain a replacement field specification inside curly brackets ({ }). It’s possible to leave the specification empty (just {}) but we can also specify the position and type of the argument to use and how the resulting value should be rendered. A few examples:

6 Chapter 2. Convert Fahrenheit to Celsius

50 Examples Documentation, Release 1.

'{!r}'.format(v) # Equivalent to repr(v) '{!s}'.format(v) # Equivalent to str(v)

Explicitly give the position of the argument to use for

each field. Results in the string "arg2 arg1"

'{1} {0}'.format('arg1', 'arg2')

We can also specify formatting details such as the number of decimal places, style of numeric display, and left- or right-alignment. This comes within the curly brackets and following a : character.

We can left-align, right-align, or center a string within a desired output width, optionally giving the character to be used for padding:

>>> '{0:<15}'.format('left-justify') 'left-justify ' >>> '{0:>15}'.format('right-justify') ' right-justify' >>> '{0:^15}'.format('centered') '**centered****'

We can output a value in binary, octal, decimal, or hexadecimal:

>>> '{0:b}'.format(1972) '11110110100' >>> '{0:o}'.format(1972) '3664' >>> '{0:d}'.format(1972) '1972' >>> '{0:x}'.format(1972) '7b4'

We can request rounding to a specific number of decimal places, exponential notation, or displaying as a percentage:

>>> '{0:d}'.format(232) '4294967296' >>> '{0:e}'.format(232) '4.294967e+09' >>> '{0:%}'.format( 45 / 70 ) '64.285714%' >>> '{0:.2%}'.format( 45 / 70 ) '64.29%'

The complete syntax for format strings is documented in the Python Library Reference at .

References

The references in each section will be to useful web pages, Wikipedia entries, software libraries, and books. Generally each reference is annotated with a short explanation of what’s in it and why it might be of interest, to help you in deciding which references to pursue.

http://books.google.com/books?id=lnmrSAAACAAJ “A Matter of Degrees: What Temperature Reveals About the Past and Future of Our Species, Planet and Universe”, by Gino Segré, is an entertaining tour through science using the concept of temperature as the connecting thread, including: biological aspects such as the regulation of

2.5. References 7

CHAPTER 3

Background: Algorithms

An algorithm specifies a series of steps that perform a particular computation or task. Algorithms were originally born as part of mathematics – the word “algorithm” comes from the Arabic writer Muammad ibn M¯us¯a al-Khw¯arizm¯ı, – but currently the word is strongly associated with computer science. Throughout this book we’ll examine a number of different algorithms to perform a variety of tasks.

Algorithms resemble recipes. Recipes tell you how to accomplish a task by performing a number of steps. For example, to bake a cake the steps are: preheat the oven; mix flour, sugar, and eggs throughly; pour into a baking pan; and so forth.

However, “algorithm” is a technical term with a more specific meaning than “recipe”, and calling something an algorithm means that the following properties are all true:

  • An algorithm is an unambiguous description that makes clear what has to be implemented. In a recipe, a step such as “Bake until done” is ambiguous because it doesn’t explain what “done” means. A more explicit description such as “Bake until the cheese begins to bubble” is better. In a computational algorithm, a step such as “Choose a large number” is vague: what is large? 1 million, 1 billion, or 100? Does the number have to be different each time, or can the same number be used on every run?
  • An algorithm expects a defined set of inputs. For example, it might require two numbers where both numbers are greater than zero. Or it might require a word, or a list of zero or more numbers.
  • An algorithm produces a defined set of outputs. It might output the larger of the two numbers, an all-uppercase version of a word, or a sorted version of the list of numbers.
  • An algorithm is guaranteed to terminate and produce a result, always stopping after a finite time. If an algorithm could potentially run forever, it wouldn’t be very useful because you might never get an answer.
  • Most algorithms are guaranteed to produce the correct result. It’s rarely useful if an algorithm returns the largest number 99% of the time, but 1% of the time the algorithm fails and returns the smallest number instead.^1
  • If an algorithm imposes a requirement on its inputs (called a precondition), that requirement must be met. For (^1) There are special situations where algorithms that are sometimes wrong can still be useful. A good example is testing whether a number is prime. There’s an algorithm called the Rabin-Miller test that’s always correct when it reports a number is composite, but has a 25% chance of being wrong when it reports a number is prime. One test therefore isn’t enough to conclude you’ve found a prime, but you can perform repeated tests and reduce the chance of being wrong to as low as you like (but never zero).

50 Examples Documentation, Release 1.

example, a precondition might be that an algorithm will only accept positive numbers as an input. If precondi- tions aren’t met, then the algorithm is allowed to fail by producing the wrong answer or never terminating.

Studying algorithms is a fundamental part of computer science. There are several different characteristics of an algorithm that are useful to know:

  1. Does an algorithm actually exist to perform a given task?
  2. If someone proposes an algorithm to solve a task, are we sure that the algorithm works for all possible inputs?
  3. How long does the algorithm take to run? How much memory space does it require?
  4. Once we know it’s possible to solve a problem with an algorithm, a natural question is whether the algorithm is the best possible one. Can the problem be solved more quickly?

Most of these questions will be discussed for the algorithms covered in this book.

An Example Algorithm

Let’s look at a very simple algorithm called find_max().

Problem: Given a list of positive numbers, return the largest number on the list.

Inputs: A list L of positive numbers. This list must contain at least one number. (Asking for the largest number in a list of no numbers is not a meaningful question.)

Outputs: A number n, which will be the largest number of the list.

Algorithm:

  1. Set max to 0.
  2. For each number x in the list L, compare it to max. If x is larger, set max to x.
  3. max is now set to the largest number in the list.

An implementation in Python:

def find_max (L): max = 0 for x in L: if x > max: max = x return max

Does this meet the criteria for being an algorithm?

  • Is it unambiguous? Yes. Each step of the algorithm consists of primitive operations, and translating each step into Python code is very easy.
  • Does it have defined inputs and outputs? Yes.
  • Is it guaranteed to terminate? Yes. The list L is of finite length, so after looking at every element of the list the algorithm will stop.
  • Does it produce the correct result? Yes. In a formal setting you would provide a careful proof of correctness. In the next section I’ll sketch a proof for an alternative solution to this problem.

10 Chapter 3. Background: Algorithms

50 Examples Documentation, Release 1.

This may seem like a trick; we showed that it’s correct for the trivial case of the single-element list, and then showed that it’s correct on a problem of a certain size. Such proofs are called inductive proofs, and they’re a well-known mathematical technique for proving a theorem.

Carrying out an inductive proof of some property requires two steps.

  1. First, you show that the property is true for some simple case: an empty list or a list of length 1, an empty set, a single point. Usually this demonstration is very simple; often it’s obviously true that the property is true. This is called the basis case.
  2. Next, you assume the property is true for size N and show that it’s true for some larger size such as N+1. This is called the inductive step, and is usually the more difficult one.

Once you have both demonstrations, you’ve proven the property is true for an infinite number of values of N; correct- ness for N=1 implies that the N=2 case is also correct, which in turn implies correctness for N=3, 4, 5, and every other positive integer. Not every theorem can be put into a form where an inductive proof can be used.

References

XXX something on induction

12 Chapter 3. Background: Algorithms

CHAPTER 4

Background: Measuring Complexity

It’s obviously most important that an algorithm solves a given problem correctly. How much time an algorithm will take to solve a problem is only slightly less important. All algorithms must terminate eventually, because they wouldn’t be algorithms if they didn’t, but they might run for billions of years before terminating. In order to compare algorithms, we need a way to measure the time required by an algorithm.

To characterize an algorithm, we really need to know how its running time changes in relation to the size of a problem. If we solve a problem that’s ten times as large, how does the running time change? If we run find_max() on a list that’s a thousand elements long instead of a hundred elements, does it take the same amount of time? Does it take 10 times as long to run, 100 times, or 5 times? This is called the algorithm’s time complexity or, occasionally, its scalability.

To measure the time complexity, we could simply implement an algorithm on a computer and time it on problems of different sizes. For example, we could run find_max() on lists from lengths ranging from 1 to 1000 and graph the results. This is unsatisfactory for two reasons:

  • Computers perform different operations at different speeds: addition may be very fast and division very slow. Different computers may have different specialities. One machine may have very fast math but slow string operations while another might do math very slowly. Machines also vary in memory size and processor, memory, and disk speeds. Researchers would find it difficult to compare results measured on different machines.
  • Measuring performance within a given range doesn’t tell us if the algorithm continues to scale outside of the range. Perhaps it runs very well for problem sizes up to 1000, but at some larger size it began to run too slowly.

Instead, the measurement is done more abstractly by counting the number of basic operations required to run the algorithm, after defining what is counted as an operation. For example, if you wanted to measure the time complexity of computing a sine function, you might assume that only addition, subtraction, multiplication, and division are basic operations. On the other hand, if you were measuring the time to draw a circle, you might include sine as a basic operation.

Complexity is expressed using big-O notation. The complexity is written as O(), meaning that the number of operations is proportional to the given function multiplied by some constant factor. For example, if an algorithm takes 2(n2) operations, the complexity is written as O(n*2), dropping the constant multiplier of 2.

Some of the most commonly seen complexities are:

50 Examples Documentation, Release 1.

References

XXX

4.1. References 15

50 Examples Documentation, Release 1.

16 Chapter 4. Background: Measuring Complexity