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.
Lists
Creating Lists I: [Square brackets]
Example:
Exercise: Create the list [63, 12, -10, "a", 12], assign it to the variable L, and print the list.
Exercise: Create the empty list (you will often need to do this).
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:
Exercise: Use range to construct the list .
Exercise: Use range to construct the list of even numbers between 1 and 100 (including 100).
Exercise: The step argument for the range command can be negative. Use range to construct the list .
Creating Lists III: list comprehensions
List comprehensions provide a concise way to create lists from other lists (or other data types).
Example We already know how to create the list :
Using a list comprehension, we can now create the list as follows:
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.
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.
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.
Project Euler, Problem 1: Find the sum of all the multiples of 3 or 5 below 1000.
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".
Nested list comprehensions
List comprehensions can be nested!
Examples:
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 .
Project Euler, Problem 9: There exists exactly one Pythagorean triplet for which . Find the product .
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]?
What is L[1]?
What is the index of the first element of L?
What is L[-1]? What is L[-2]?
What is L.index(2)? What is L.index(3)?
Modifying lists: changing an element in a list
To change the item in position i of a list L:
Modifying lists: append and extend
To append an object to a list:
To extend a list by another list:
Modifying lists: reverse, sort, ...
Concatenating Lists
To concatenate two lists, add them with the operator +. This is not a commutative operation....
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.
Advanced exercise: The following function combines a loop with the some of the list operations above. What does the function do?
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:
We can create a tuple from a list, or vice-versa.
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.
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:
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):
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"] |
A dictionary can have the same value multiple times, but each key must only appear once and must be "immutable".
Another way to add items to a dictionary is with the update() method which updates the dictionnary from another dictionnary:
We can iterate through the keys, or values, or both, of a dictionary.
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], ... }
Then try
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.
Whereas dividing a Sage Integer by a Sage Integer gives a rational number:
Modifying lists has consequences!
Try to predict the results of the following commands.
Now try these:
You can use the command deepcopy to avoid these issues.
The same issues occur with dictionaries.
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.
Note that the truth value expression in the while loop is evaluated using bool().
For Loops
Here is a basic for loop iterating over all of the elements in the list l:
The range function is very useful when you want to generate arithmetic progressions to loop over. Note that the end point is never included:
You can use the continue keyword to immediately go to the next item in the loop:
If you want to break out of the loop, use the break keyword:
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:
It's cleaner to use enumerate which provides the index as well as the value:
You could make something similary to the enumerate function by using zip to zip two lists together:
For loops work using Python's iterator protocol. This allows all sorts of different objects to be looped over. For example,
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:
The odd integers between and .
The first odd integers.
The integers between and that are neither divisible by nor by nor by .
The first integers between and that are neither divisible by nor by nor by .
Functions
Functions are defined using the def statement, and values are returned using the return keyword:
Default arguments for functions
You can give default values for arguments in functions:
You can return multiple things from a function:
You can also take variable number of arguments and keyword arguments in a function:
Let's use the yield instruction to make a generator for the Fibonacci numbers less than :
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.