Math302: Sage Lab 1

511 days ago by jtmulhol



Math 302: Sage Lab 1
Getting Started with SAGE

J. Mulholland
Dept. of Mathemtics, SFU


Contents:
  1. Introduction
  2. Variables and Statements
  3. Lists
  4. Sets
  5. Exercises


1) Introduction

Ted Kosen, author of SAGE For Newbies, describes SAGE as follows:

SAGE is an open source mathematics computing environment for performing symbolic, algebraic, and numerical computations. Mathematics computing environments are complex, and require a significant amount of time and effort to become proficient at using one. It will take a beginner a while to become an expert in using SAGE, but fortunately one does not need to be a SAGE expert in order to begin using it to solve problems.

This is precisely the viewpoint we will take in this course. We will not attempt to become SAGE experts, we will however us it to solve problems. In particular, problems regarding permutation puzzles.

A mathematics computing environment is a collection of computer algorithms, and data structures, that are built on top of a programming language. This means one has access to a full programming language, in SAGE's case it is PYTHON, and further access to a mathematical objects library complete with algorithms for performing calculations.

Rather than say anything more about what SAGE is, let's just see for ourselves what it can do.

We can use it like a calculator to add/subtract/multiply/divide numbers.

2+3 
       
5
5

When typing input, [enter] will jump you down to the next line, whereas [shit-enter] gets SAGE to evaluate the code-block. You can also press the [evaluate] link below the active cell instead of [shift-enter].

A bit of terminology:
What is typed in a cell is called the source code.
When the cell is executed, what SAGE prints to the screen (blue writing) is called the output.

So "2+5" in the cell above is the source code, and "5" is the output.



1.1) Arithmetic Operations

operation syntax name
addition
+
subtraction
-
multiplication
*
division
/
remainder
%
exponents
^ or **

3+2/5*2^3 
       
31/5
31/5
2^3 
       
8
8
2**3 
       
8
8
5^3^2 
       
1953125
1953125
(5^3)^2 
       
15625
15625
11%4 
       
3
3

As you can see, SAGE follows the usual order of operations:

  1. first evaluate exponents from right to left,
  2. then multiplication, division, and remainder from left to right
  3. finally, addition and subtraction from left to right.

You can change the order in which expressions are evaluated by using parenthesis: ( ).

For you to try: Try some of your own calculations in the cell below. 

 
       


1.2) Inserting a New Cell

A new cell will automatically appear below the last cell of your sheet, when the contents of the last cell have been evaluated.  Sometimes, however, we would like to add a new cell in the middle of our worksheet.  To insert a new execution shell in the worksheet, you can:

Hover the mouse slightly above or below the current cell, until a purple horizontal line appears, then click the line. This will add a cell where you clicked.

If you just want to add a cell, or a bunch of cells, at the end of the worksheet, just select the last cell and hit [shift-enter] to add a new cell.

For you to try: Add a new cell below this cell. Also, add a new cell above it.

 
       


1.3) Working in a Cell: Enter, Shift-Enter, The Semicolon, and Comments

Multiple statements can be placed in a single cell. After typing "1+2", use [enter] to bring the cursor down to the next line. Notice when the cell is evaluated (either [shift-enter] or click [evaluate] below cell), only the output of the last line of code was displayed.
1+2 3-2 
       
1
1

To display both outputs we can place the statements on the same line, separating them by semicolons ";". In SAGE, semicolons can be placed after statements as optional terminators, but most of the time one will only see them used to place multiple statements on the same line.

1+2;3-2; 
       
3
1
3
1

There is also a "print" command for sending outputs to the screen. We'll see this in section 2.2 below.

It will come in handy to be able to add comments directly in the source code. Comments are basically notes to yourself about what you are doing, and are not intended for the computer to execute. Anything followed by the "#" symbol is treated as a comment.

#this is a comment 2-3 # and this is another comment after some code 
       
-1
-1
When a comment is too long to fit in one line, we can enclose it in triple quotes: """ text here """.
"""here is a really long comment. What the next line does is evaluates 3 expressions all on the same line. Nothing special, but my comment is now pretty long.""" 5^4; 4+2*3; 
       
625
10
625
10




2) Variables and Statements

Part of the power of a computing environment lies in the ability to store and recall information. This is done using "variables" and "statements".

2.1) Variables

A variable is a name that is associated with the data stored in a memory address. One way to create variables in SAGE is through assignment which consists of placing the variable you would like to create to the left of an equal sign "=", and the expression on the right side.

Here we create a variable "a", and assign to it the number 5.

a=5 
       
b=7 # create a new variable b and assign 7 to it. a=3 # reassign to the variable a, the number 3. 
       
c=a+b # assign to the variable c the sum of a and b c # output the value of c 
       
10
10


2.2) Statements

Statements are the part of a programming language that are used to encode algorithmic logic.

Simple statements:

  • assignment:
       a= a + 1
  • call:
       var(x), print(a+1), factor(24)
  • assumption:
       assume(x > 0)


Compound statements
  • if-statement:
       if A>3:
         print(A-3)
       else:
         print("not big enough")
  • while-statement:
       while x<= 10:
         print x
         x = x+1
  • for-statement:
       for x in [1,2,3,4,5]:
          print x

We will look at if , while , and for statements more thoroughly later. But the odd one may creep into some of our examples below.

print()
SAGE has a statement called "print" that allows the results of expressions to be displayed regardless of where they are located in the cell.

a=3 b=2 print a,b 
       
3 2
3 2

We could also have used semicolons to get a and b on the same line. Notice though, this displays a and b on separate lines in the output, whereas "print" puts them on the same line.

a=3;b=2; a;b; 
       
3
2
3
2
if is_prime(5): # is_prime() is a built-in function print("5 is prime") else: print("5 is not prime") 
       
5 is prime
5 is prime


3) Lists

Lists are one of the most fundamental objects in any programming language.

3.1) Defining a List

A list is defined by putting the items of the list, separated by commas, inside square brackets "[ ]".
L=[1,2,"milk","cheese","new shoes"] print L 
       
[1, 2, 'milk', 'cheese', 'new shoes']
[1, 2, 'milk', 'cheese', 'new shoes']

We can select items from the list as follows. (Note: the first item in a SAGE/Python list is indexed by 0, not 1 as you may have expected.)

L[0] #select the first item (indexed by 0) from the list 
       
1
1
L[4] # select the last item 
       
'new shoes'
'new shoes'
L[5] # what if there is no item with the index you've input 
       
Traceback (click to the left of this block for traceback)
...
IndexError: list index out of range
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_12.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("TFs1XSAgICMgd2hhdCBpZiB0aGVyZSBpcyBubyBpdGVtIHdpdGggdGhlIGluZGV4IHlvdSd2ZSBpbnB1dA=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmpa4YqOI/___code___.py", line 3, in <module>
    exec compile(u"L[_sage_const_5 ]   # what if there is no item with the index you've input" + '\n', '', 'single')
  File "", line 1, in <module>
    
IndexError: list index out of range

Order matters in a list. If items are in different orders, then the list are not equal.

[1,2,3]==[2,1,3] 
       
False
False

We can also create a list by stating conditions we want the elements to satisfy. This usually requires starting with a bigger list, and either constructing a sublist, or constructing a new list.

[n for n in [1,2,3,4] if is_even(n)] # selects the even integers 
       
[2, 4]
[2, 4]
[2*n+1 for n in [1,2,3,4]] # creates a new list of odd integers from old list 
       
[3, 5, 7, 9]
[3, 5, 7, 9]
L=[1,2,3] 
       
L.remove(3) # removes item 3 from L L 
       
[1, 2]
[1, 2]
L.append(4) #adds item 4 to the end of list L L 
       
[1, 2, 4]
[1, 2, 4]
len(L) # returns the length of the list 
       
3
3
 
       
Here are some more list operations. We won't really use any of them, but just in case you are curious.

list.append(x)
     Add an item to the end of the list.

list.extend(L)
     Extend the list by appending all the items in the given list.

list.insert(i, x)
     Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)
     Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])
     Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)
     Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)
     Return the number of times x appears in the list.

list.sort()
     Sort the items of the list, in place.

list.reverse()
     Reverse the elements of the list, in place.



3.3) Built-in Lists

SAGE (and Python) already have some built-in lists that we can use. The range function, range(a,b), creates the list of integers beginning with a and ending at b-1. Here we assume a is less than b.

range(1,11) # creates a list of integers from 1 to 10 
       
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1..10] # another way to construct the list 
       
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We can select one or multiple items from a list as follows.

L=range(1,26) print L[1] # selects item of index 1 print L[0:3] # sublist of L consisting of items indexed 0 through 3 
       
2
[1, 2, 3]
2
[1, 2, 3]

The items in a list can be overwritten by new items, as the following shows.

L=[1,2,3,4] L 
       
[1, 2, 3, 4]
[1, 2, 3, 4]
L[1]=5 L 
       
[1, 5, 3, 4]
[1, 5, 3, 4]

An example of using lists to factor all integers from 1 to 10.

[factor(n) for n in range(1,11)] 
       
[1, 2, 3, 2^2, 5, 2 * 3, 7, 2^3, 3^2, 2 * 5]
[1, 2, 3, 2^2, 5, 2 * 3, 7, 2^3, 3^2, 2 * 5]


4) Sets

Sage has a built-in Set type. It offers a fast lookup of whether an element is in the set or not, and it come equipped with standard set-theoretic operations: union, intersection, etc.

Unlike lists, where order matters, the order of the elements in a set does not matter. All the matters is the elements themselves. So in this sense, we can think of sets as unordered lists.



4.1) Defining a Set

Set([1,2,3]) # here we turn the list [1,2,3] into a set 
       
{1, 2, 3}
{1, 2, 3}
Set([1,2,3])==Set([2,1,3]) # order doesn't matter in a set 
       
True
True
Set(range(1,101)) # using the range list to construct a set 
       
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}

Another way to construct the same set:

Set(1..100) 
       
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}

We can construct sets by specifying conditions on the elements, much like we did with lists.

Set(x for x in range(1,11) if is_even(x)) 
       
{8, 2, 4, 10, 6}
{8, 2, 4, 10, 6}
Set(x for x in range(1,51) if x%3==0) # integers divisible by 3 
       
{33, 3, 36, 6, 39, 9, 42, 12, 45, 15, 48, 18, 21, 24, 27, 30}
{33, 3, 36, 6, 39, 9, 42, 12, 45, 15, 48, 18, 21, 24, 27, 30}

There is also a filter command for selecting elements satisfying some special condition. Here we select the prime numbers.

S=Set(1..20) filter(is_prime,S) 
       
[2, 3, 5, 7, 11, 13, 17, 19]
[2, 3, 5, 7, 11, 13, 17, 19]


4.2) Set Operations

We have all the usual set operations available.
S=Set([1,2,"milk"]) "milk" in S # we can use "in" to check if an element is in a set 
       
True
True
A=Set([1,2,3,4]); B=Set([3,4,5,6]); 
       
A.cardinality() 
       
4
4
3 in A 
       
True
True
6 in A 
       
False
False
A.union(B) 
       
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
A.intersection(B) 
       
{3, 4}
{3, 4}
A.difference(B) 
       
{1, 2}
{1, 2}
CartesianProduct(A,B) 
       
Cartesian product of {1, 2, 3, 4}, {3, 4, 5, 6}
Cartesian product of {1, 2, 3, 4}, {3, 4, 5, 6}
CartesianProduct(A,B).list() 
       
[[1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5], [2, 6], [3, 3],
[3, 4], [3, 5], [3, 6], [4, 3], [4, 4], [4, 5], [4, 6]]
[[1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5], [2, 6], [3, 3], [3, 4], [3, 5], [3, 6], [4, 3], [4, 4], [4, 5], [4, 6]]


4.3) Built-in Sets

SAGE comes loaded with many common mathematical sets: integers ZZ, natural numbers NN, real numbers RR, etc.

ZZ 
       
Integer Ring
Integer Ring
1 in ZZ 
       
True
True
1/2 in ZZ 
       
False
False
0 in NN # NN denotes the natural numbers 
       
True
True
-1 in NN 
       
False
False
This has been a quick introduction to get you up and running in this class. We will be developing our experience with SAGE over the term. So have fun!


5) Exercises

Exercise 1: Assign 27 to the variable a, 1027 to the variable b, and the product to the variable c. Have SAGE output the values of all three variables.

 
       

Exercise 2: For a, b and c in Exercise 1, use the factor() command to factor c. Also, use the remainder command % to determine is 16 is a factor of ab+1.

 
       

Exercise 3: Create and print a list of integers from 50 to 100 (inclusive).

 
       

Exercise 4: From the list in Exercise 3, create a sublist consisting of (a) even integers, (b) odd integers, (c) primes, and (d) numbers divisible by 13.

 
       

Exercise 5: Create the two sets A={1,2,3,4,5,6}, B={2,4,6,8,10} and find (a) their intersection, (b) their union, and (c) the cardinality of their cartesian product.