%html
Tutorial: Programming in Python and Sage
Authors: Florent Hivert <[email protected]>, Franco Saliola <[email protected]>, et al.
This tutorial explores the different data structures in Python (and Sage) as well as control structures and Python functions.
The exercises below are extracted from the Sage Thematic Tutorial on Programming in Python and Sage.
The thematic tutorial also contains detailed information on the data structures, control structures and functions.
%html
Lists
Creating Lists I: [Square brackets]
Example:
%html
Exercise: Create the list [63, 12, -10, "a", 12], assign it to the variable L, and print the list.
%html
Exercise: Create the empty list (you will often need to do this).
%html
Creating Lists II: range
The range function provides an easy way to construct a list of integers. Here is the documentation of the range function:
%html
Exercise: Use range to construct the list .
%html
Exercise: Use range to construct the list of even numbers between 1 and 100 (including 100).
%html
Using a list comprehension, we can now create the list as follows:
%html
Exercise: [Project Euler, Problem 6]
The sum of the squares of the first ten natural numbers is The square of the sum of the first ten natural numbers is Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
%html
Filtering lists with a list comprehension
A list can be filtered using a list comprehension.
Example: To create a list of the squares of the prime numbers between 1 and 100, we use a list comprehension as follows.
%html
Exercise: Use a list comprehension to list all the natural numbers below 20 that are multiples of 3 or 5. Hint:
- To get the remainder of 7 divided by 3 use 7%3.
- To test for equality use two equal signs (==); for example, 3 == 7.
%html
Project Euler, Problem 1: Find the sum of all the multiples of 3 or 5 below 1000.
%html
Fizz Buzz
Écrire une fonction qui affiche les nombres de 1 à 100 de sorte que la fonction affiche "Fizz" au lieu d'afficher les multiples de 3 et "Buzz" au lieu des multiples de 5. Pour les multiples de 3 et 5, afficher "FizzBuzz".
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
%html
Nested list comprehensions
List comprehensions can be nested!
Examples:
%html
Exercise:
A Pythagorean triple is a triple of positive integers satisfying . The Pythagorean triples whose components are at most are:
Using a filtered list comprehension, construct the list of Pythagorean triples whose components are at most .
%html
Project Euler, Problem 9: There exists exactly one Pythagorean triplet for which . Find the product .
%html
Accessing individual elements of lists
To access an element of the list, use the syntax L[i], where is the index of the item.
Exercise:
Construct the list L = [1,2,3,4,3,5,6]. What is L[3]?
%html
What is L[1]?
%html
What is the index of the first element of L?
%html
What is L[-1]? What is L[-2]?
%html
What is L.index(2)? What is L.index(3)?
%html
Modifying lists: changing an element in a list
To change the item in position i of a list L:
%html
%html
Modifying lists: append and extend
To append an object to a list:
%html
%html
To extend a list by another list:
%html
%html
Modifying lists: reverse, sort, ...
%html
%html
%html
%html
Concatenating Lists
To concatenate two lists, add them with the operator +. This is not a commutative operation....
%html
Slicing Lists
You can slice a list using the syntax L[start : stop : step]. This will return a sublist of L.
Exercise: Below are some examples of slicing lists. Try to guess what the output will be before evaluating the cell.
%html
%html
%html
%html
%html
%html
%html
Advanced exercise: The following function combines a loop with the some of the list operations above. What does the function do?
%html
%html
Tuples
A tuple is an immutable list. That is, it cannot be changed once it is created. To create a tuple, use parentheses instead of brackets:
%html
We can create a tuple from a list, or vice-versa.
%html
%html
Tuples behave like lists in many respects:
Operation | Syntax for lists | Syntax for tuples |
---|---|---|
Accessing a letter | list[3] | tuple[3] |
Concatenation | list1 + list2 | tuple1 + tuple2 |
Slicing | list[3:17:2] | tuple[3:17:2] |
A reversed copy | list[::-1] | tuple[::-1] |
Length | len(list) | len(tuple) |
Trying to modify a tuple will fail.
%html
Dictionaries
A dictionary is another built-in data type. Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable object. Strings and numbers can always be keys (because they are immutable). Dictionaries are sometimes called "associative arrays" in other programming languages.
There are several ways to define dictionaries. One method is to use braces, {}, with comma-separated entries given in the form key:value:
%html
A second solution for creating a dictionary is to use the function dict which admits a list of 2-tuples (key, value) (actually any iterable):
%html
Dictionaries behave as lists and tuples for several important operations.
Operation | Syntax for lists | Syntax for dictionaries |
---|---|---|
Accessing elements | list[3] | D["key"] |
Length | len(list) | len(D) |
Modifying | L[3] = 17 | D["key"] = 17 |
Deleting items | del L[3] | del D["key"] |
%html
A dictionary can have the same value multiple times, but each key must only appear once and must be "immutable".
%html
Another way to add items to a dictionary is with the update() method which updates the dictionnary from another dictionnary:
%html
%html
We can iterate through the keys, or values, or both, of a dictionary.
%html
%html
%html
%html
%html
Exercise: Consider the following directed graph.
Create a dictionary whose keys are the vertices of the above directed graph, and whose values are the lists of the vertices that it points to. For instance, the vertex 1 points to the vertices 2 and 3, so the dictionary will look like:
d = { ..., 1:[2,3], ... }
%html
Then try
%html
Using Sage types: The srange command
Example: Construct a matrix whose entry is the rational number . The integer generated by range are python int. As a consequence, dividing them does euclidian division.
%html
Whereas dividing a Sage Integer by a Sage Integer gives a rational number:
%html
Modifying lists has consequences!
Try to predict the results of the following commands.
%html
%html
Now try these:
%html
%html
%html
You can use the command deepcopy to avoid these issues.
%html
%html
The same issues occur with dictionaries.
%html
Loops and Functions
For more verbose explanation of what's going on here, a good place to look is at the following section of the Python tutorial: http://docs.python.org/tutorial/controlflow.html
While Loops
While loops tend not to be used nearly as much as for loops in Python code.
%html
Note that the truth value expression in the while loop is evaluated using bool().
%html
%html
For Loops
Here is a basic for loop iterating over all of the elements in the list l:
%html
The range function is very useful when you want to generate arithmetic progressions to loop over. Note that the end point is never included:
%html
You can use the continue keyword to immediately go to the next item in the loop:
%html
If you want to break out of the loop, use the break keyword:
%html
If you need to keep track of both the position in the list and its value, one (not so elegant) way would be to do the following:
%html
It's cleaner to use enumerate which provides the index as well as the value:
%html
You could make something similary to the enumerate function by using zip to zip two lists together:
%html
For loops work using Python's iterator protocol. This allows all sorts of different objects to be looped over. For example,
%html
Exercise
For each of the following sets, compute the list of its elements and their sum. Use two different ways, if possible: with a loop; and using a list comprehension.
-
The first terms of the harmonic series:
%html
The odd integers between and .
%html
The first odd integers.
%html
The integers between and that are neither divisible by nor by nor by .
%html
The first integers between and that are neither divisible by nor by nor by .
%html
Functions
Functions are defined using the def statement, and values are returned using the return keyword:
%html
%html Here is a function that returns the -th Fibonacci number.
%html And here is a list of the first twenty Fibonacci numbers.
%html
Default arguments for functions
You can give default values for arguments in functions:
%html
%html
%html
%html
You can return multiple things from a function:
%html
You can also take variable number of arguments and keyword arguments in a function:
%html
%html
Let's use the yield instruction to make a generator for the Fibonacci numbers less than :
%html
Exercices
- Write a function is_even returning True if n is even and False otherwise.
- Write a function every_other which takes a list l and returns a list containing every other element of l
- Write a function computing the -th Fibonacci number. Try to improve performance.