Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download
Project: Public Code
Views: 82

Introduction to Sage and Python

Worksheet

This is a public CoCalc worksheet. If you want to run it, you need to create a CoCalc account and a new project, then click on the "i" on top left and copy this worksheet to your project.

A worksheet is made of cells. Some contain text and some contain code that you can run directly.

5+12
17

Sage as a calculator

4/5 12//5 (4/5).n() 4./5. .8
4/5 2 0.800000000000000 0.800000000000000 0.800000000000000
pi.n(digits=300)
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127
x = var('x') expr = 1 / (1-x^2) expr
-1/(x^2 - 1)
1x21\displaystyle -\frac{1}{x^{2} - 1}
show(expr)
1x21\displaystyle -\frac{1}{x^{2} - 1}
latex(expr)
-\frac{1}{x^{2} - 1}
expr2 = - expr + expr^3 show(expr2)
1x211(x21)3\displaystyle \frac{1}{x^{2} - 1} - \frac{1}{{\left(x^{2} - 1\right)}^{3}}
show(expr2.simplify_rational())
x42x2x63x4+3x21\displaystyle \frac{x^{4} - 2 \, x^{2}}{x^{6} - 3 \, x^{4} + 3 \, x^{2} - 1}
expr2.subs(x = pi)
1/(pi^2 - 1) - 1/(pi^2 - 1)^3
expr2.subs(x = pi).n()
0.111311464472836

The help system

How can you find what you are looking for?

--> The tab key and the "?"

A = matr
File: /projects/sage/sage-7.3/src/sage/matrix/constructor.pyx Signature : matrix(self, ring=None, nrows=None, ncols=None, sparse=None, *args) Docstring : Create a matrix. This implements the "matrix" constructor: sage: matrix([[1,2],[3,4]]) [1 2] [3 4] It also contains methods to create special types of matrices, see "matrix.[tab]" for more options. For example: sage: matrix.identity(2) [1 0] [0 1] INPUT: The matrix command takes the entries of a matrix, optionally preceded by a ring and the dimensions of the matrix, and returns a matrix. The entries of a matrix can be specified as a flat list of elements, a list of lists (i.e., a list of rows), a list of Sage vectors, a callable object, or a dictionary having positions as keys and matrix entries as values (see the examples). If you pass in a callable object, then you must specify the number of rows and columns. You can create a matrix of zeros by passing an empty list or the integer zero for the entries. To construct a multiple of the identity (cI), you can specify square dimensions and pass in c. Calling matrix() with a Sage object may return something that makes sense. Calling matrix() with a NumPy array will convert the array to a matrix. The ring, number of rows, and number of columns of the matrix can be specified by setting the "ring", "nrows", or "ncols" keyword parameters or by passing them as the first arguments to the function in specified order. The ring defaults to "ZZ" if it is not specified and cannot be determined from the entries. If the number of rows and columns are not specified and cannot be determined, then an empty 0x0 matrix is returned. INPUT: * "ring" -- the base ring for the entries of the matrix. * "nrows" -- the number of rows in the matrix. * "ncols" -- the number of columns in the matrix. * "sparse" -- create a sparse matrix. This defaults to "True" when the entries are given as a dictionary, otherwise defaults to "False". * "entries" -- see examples below. OUTPUT: a matrix EXAMPLES: sage: m = matrix(2); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring sage: m = matrix(2,3); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m = matrix(QQ,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m = matrix(QQ, 3, 3, lambda i, j: i+j); m [0 1 2] [1 2 3] [2 3 4] sage: m = matrix(3, lambda i,j: i-j); m [ 0 -1 -2] [ 1 0 -1] [ 2 1 0] sage: matrix(QQ, 2, 3, lambda x, y: x+y) [0 1 2] [1 2 3] sage: matrix(QQ, 5, 5, lambda x, y: (x+1) / (y+1)) [ 1 1/2 1/3 1/4 1/5] [ 2 1 2/3 1/2 2/5] [ 3 3/2 1 3/4 3/5] [ 4 2 4/3 1 4/5] [ 5 5/2 5/3 5/4 1] sage: v1=vector((1,2,3)) sage: v2=vector((4,5,6)) sage: m = matrix([v1,v2]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m = matrix(QQ,2,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m = matrix(QQ,2,3,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m = matrix({(0,1): 2, (1,1):2/5}); m; m.parent() [ 0 2] [ 0 2/5] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m = matrix(QQ,2,3,{(1,1): 2}); m; m.parent() [0 0 0] [0 2 0] Full MatrixSpace of 2 by 3 sparse matrices over Rational Field sage: import numpy sage: n = numpy.array([[1,2],[3,4]],float) sage: m = matrix(n); m; m.parent() [1.0 2.0] [3.0 4.0] Full MatrixSpace of 2 by 2 dense matrices over Real Double Field sage: v = vector(ZZ, [1, 10, 100]) sage: m = matrix(v); m; m.parent() [ 1 10 100] Full MatrixSpace of 1 by 3 dense matrices over Integer Ring sage: m = matrix(GF(7), v); m; m.parent() [1 3 2] Full MatrixSpace of 1 by 3 dense matrices over Finite Field of size 7 sage: g = graphs.PetersenGraph() sage: m = matrix(g); m; m.parent() [0 1 0 0 1 1 0 0 0 0] [1 0 1 0 0 0 1 0 0 0] [0 1 0 1 0 0 0 1 0 0] [0 0 1 0 1 0 0 0 1 0] [1 0 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 0 1 1 0] [0 1 0 0 0 0 0 0 1 1] [0 0 1 0 0 1 0 0 0 1] [0 0 0 1 0 1 1 0 0 0] [0 0 0 0 1 0 1 1 0 0] Full MatrixSpace of 10 by 10 dense matrices over Integer Ring sage: matrix(ZZ, 10, 10, range(100), sparse=True).parent() Full MatrixSpace of 10 by 10 sparse matrices over Integer Ring sage: R = PolynomialRing(QQ, 9, 'x') sage: A = matrix(R, 3, 3, R.gens()); A [x0 x1 x2] [x3 x4 x5] [x6 x7 x8] sage: det(A) -x2*x4*x6 + x1*x5*x6 + x2*x3*x7 - x0*x5*x7 - x1*x3*x8 + x0*x4*x8 AUTHORS: * William Stein: Initial implementation * Jason Grout (2008-03): almost a complete rewrite, with bits and pieces from the original implementation * Jeroen Demeyer (2016-02-05): major clean up, see https://trac.sagemath.org/20015 and https://trac.sagemath.org/20016
A = matrix([[1,2],[3,4]])
A
[1 2] [3 4]
type(A)
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>
A.parent()
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
A. ︠7829edf7-97ff-48d3-9879-1eed3461093b︠ A.rank
A.rank?
File: /projects/sage/sage-7.3/src/sage/matrix/matrix_integer_dense.pyx Signature : A.rank(self, algorithm='modp') Docstring : Return the rank of this matrix. INPUT: * "algorithm" -- either "'modp'" (default) or "'flint'" or "'linbox'" OUTPUT: * a nonnegative integer -- the rank Note: The rank is cached. ALGORITHM: If set to "'modp'", first check if the matrix has maximum possible rank by working modulo one random prime. If not, call LinBox's rank function. EXAMPLES: sage: a = matrix(ZZ,2,3,[1..6]); a [1 2 3] [4 5 6] sage: a.rank() 2 sage: a = matrix(ZZ,3,3,[1..9]); a [1 2 3] [4 5 6] [7 8 9] sage: a.rank() 2 Here is a bigger example - the rank is of course still 2: sage: a = matrix(ZZ,100,[1..100^2]); a.rank() 2
A.rank??
File: /projects/sage/sage-7.3/src/sage/matrix/matrix_integer_dense.pyx Source: def rank(self, algorithm='modp'): """ Return the rank of this matrix. INPUT: - ``algorithm`` -- either ``'modp'`` (default) or ``'flint'`` or ``'linbox'`` OUTPUT: - a nonnegative integer -- the rank .. NOTE:: The rank is cached. ALGORITHM: If set to ``'modp'``, first check if the matrix has maximum possible rank by working modulo one random prime. If not, call LinBox's rank function. EXAMPLES:: sage: a = matrix(ZZ,2,3,[1..6]); a [1 2 3] [4 5 6] sage: a.rank() 2 sage: a = matrix(ZZ,3,3,[1..9]); a [1 2 3] [4 5 6] [7 8 9] sage: a.rank() 2 Here is a bigger example - the rank is of course still 2:: sage: a = matrix(ZZ,100,[1..100^2]); a.rank() 2 TESTS:: sage: a.rank(algorithm='funky') Traceback (most recent call last): ... ValueError: algorithm must be one of 'modp', 'flint' or 'linbox' """ if algorithm not in ['modp', 'flint', 'linbox']: raise ValueError("algorithm must be one of 'modp', 'flint' " "or 'linbox'") r = self.fetch('rank') if not r is None: return r if algorithm == 'flint' or (self._nrows <= 6 and self._ncols <= 6 and self.height().ndigits() <= 100): r = fmpz_mat_rank(self._matrix) self.cache('rank', r) return r elif algorithm == 'modp': # Can very quickly detect full rank by working modulo p. r = self._rank_modp() if r == self._nrows or r == self._ncols: self.cache('rank', r) return r # Algorithm is 'linbox' or detecting full rank didn't work -- # use LinBox's general algorithm. r = self._rank_linbox() self.cache('rank', r) return r
A._rank_linbox

Some simple things

f(x) = x^3 + x - 4 f
x |--> x^3 + x - 4
f(7)
346
f.derivative()
x |--> 3*x^2 + 1
plot(f)

Some python

variables

a = 3 type(a)
a = "123" type(a)

lists

l = [2,3,1,5] l
l[0]
l = ["a","b",3,4.5] l
range(5)
l = [3*i for i in range(5)]

control structures

b = 8 if b%2==0: a = b/2 else: a = 3*b +1
a
if b==8: a = 3 c = 4
for i in xrange(3): print i
l = [2,4,5,68] for i in l: print i
a = 5 while a!=1: print a if a%2==0: a/=2 else: a=a*3+1
def my_function(a): if(a%2): return a*3+1 else: return a/2
my_function(5)

Some combinatorics

P = Permutations(4) P
Standard permutations of 4
list(P)
[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]]
P = Permutations(10) P
Standard permutations of 10
P.cardinality()
3628800
P.random_element()
[7, 5, 10, 6, 4, 9, 3, 8, 1, 2]
P.identity()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p = Permutation([1,5,3,4,2,7,6])
p
[1, 5, 3, 4, 7, 2, 6]
p.parent()
Standard permutations
Permutations()
Standard permutations
p.number_of_descents()
3

Lets compute the average number of fixed points...

p.number_of_fixed_points()
3
P5 = Permutations(5)
mean([p.number_of_fixed_points() for p in P5])
1
P6 = Permutations(6)
mean([p.number_of_fixed_points() for p in P6])
1
P100 = Permutations(100)
mean([P100.random_element().number_of_fixed_points() for i in range(100)])
101/100
P100.random_element??
File: /projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/combinat/permutation.py Source: def random_element(self): """ EXAMPLES:: sage: Permutations(4).random_element() [1, 2, 4, 3] """ return self.element_class(self, sample(xrange(1,self.n+1), self.n))
sample?
File: /projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/misc/prandom.py Signature : sample() Docstring : Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60) EXAMPLES: sage: sample(["Here", "I", "come", "to", "save", "the", "day"], 3) ['Here', 'to', 'day'] sage: sample(xrange(2^30), 7) [357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848]
Permutations?
File: /projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/combinat/permutation.py Signature : Permutations(self, x=0, *args, **kwds) Docstring : Permutations. "Permutations(n)" returns the class of permutations of "n", if "n" is an integer, list, set, or string. "Permutations(n, k)" returns the class of length-"k" partial permutations of "n" (where "n" is any of the above things); "k" must be a nonnegative integer. A length-k partial permutation of n is defined as a k-tuple of pairwise distinct elements of { 1, 2, ..., n }. Valid keyword arguments are: 'descents', 'bruhat_smaller', 'bruhat_greater', 'recoils_finer', 'recoils_fatter', 'recoils', and 'avoiding'. With the exception of 'avoiding', you cannot specify "n" or "k" along with a keyword. "Permutations(descents=(list,n))" returns the class of permutations of n with descents in the positions specified by "list". This uses the slightly nonstandard convention that the images of 1,2,...,n under the permutation are regarded as positions 0,1,...,n-1, so for example the presence of 1 in "list" signifies that the permutations pi should satisfy pi(2) > pi(3). Note that "list" is supposed to be a list of positions of the descents, not the descents composition. It does *not* return the class of permutations with descents composition "list". "Permutations(bruhat_smaller=p)" and "Permutations(bruhat_greater=p)" return the class of permutations smaller-or-equal or greater-or-equal, respectively, than the given permutation "p" in the Bruhat order. (The Bruhat order is defined in "bruhat_lequal()". It is also referred to as the *strong* Bruhat order.) "Permutations(recoils=p)" returns the class of permutations whose recoils composition is "p". Unlike the "descents=(list, n)" syntax, this actually takes a *composition* as input. "Permutations(recoils_fatter=p)" and "Permutations(recoils_finer=p)" return the class of permutations whose recoils composition is fatter or finer, respectively, than the given composition "p". "Permutations(n, avoiding=P)" returns the class of permutations of "n" avoiding "P". Here "P" may be a single permutation or a list of permutations; the returned class will avoid all patterns in "P". EXAMPLES: sage: p = Permutations(3); p Standard permutations of 3 sage: p.list() [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] sage: p = Permutations(3, 2); p Permutations of {1,...,3} of length 2 sage: p.list() [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] sage: p = Permutations(['c', 'a', 't']); p Permutations of the set ['c', 'a', 't'] sage: p.list() [['c', 'a', 't'], ['c', 't', 'a'], ['a', 'c', 't'], ['a', 't', 'c'], ['t', 'c', 'a'], ['t', 'a', 'c']] sage: p = Permutations(['c', 'a', 't'], 2); p Permutations of the set ['c', 'a', 't'] of length 2 sage: p.list() [['c', 'a'], ['c', 't'], ['a', 'c'], ['a', 't'], ['t', 'c'], ['t', 'a']] sage: p = Permutations([1,1,2]); p Permutations of the multi-set [1, 1, 2] sage: p.list() [[1, 1, 2], [1, 2, 1], [2, 1, 1]] sage: p = Permutations([1,1,2], 2); p Permutations of the multi-set [1, 1, 2] of length 2 sage: p.list() [[1, 1], [1, 2], [2, 1]] sage: p = Permutations(descents=([1], 4)); p Standard permutations of 4 with descents [1] sage: p.list() [[1, 3, 2, 4], [1, 4, 2, 3], [2, 3, 1, 4], [2, 4, 1, 3], [3, 4, 1, 2]] sage: p = Permutations(bruhat_smaller=[1,3,2,4]); p Standard permutations that are less than or equal to [1, 3, 2, 4] in the Bruhat order sage: p.list() [[1, 2, 3, 4], [1, 3, 2, 4]] sage: p = Permutations(bruhat_greater=[4,2,3,1]); p Standard permutations that are greater than or equal to [4, 2, 3, 1] in the Bruhat order sage: p.list() [[4, 2, 3, 1], [4, 3, 2, 1]] sage: p = Permutations(recoils_finer=[2,1]); p Standard permutations whose recoils composition is finer than [2, 1] sage: p.list() [[1, 2, 3], [1, 3, 2], [3, 1, 2]] sage: p = Permutations(recoils_fatter=[2,1]); p Standard permutations whose recoils composition is fatter than [2, 1] sage: p.list() [[1, 3, 2], [3, 1, 2], [3, 2, 1]] sage: p = Permutations(recoils=[2,1]); p Standard permutations whose recoils composition is [2, 1] sage: p.list() [[1, 3, 2], [3, 1, 2]] sage: p = Permutations(4, avoiding=[1,3,2]); p Standard permutations of 4 avoiding [1, 3, 2] sage: p.list() [[4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1], [3, 4, 1, 2], [3, 4, 2, 1], [2, 3, 4, 1], [3, 2, 4, 1], [1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [3, 1, 2, 4], [3, 2, 1, 4]] sage: p = Permutations(5, avoiding=[[3,4,1,2], [4,2,3,1]]); p Standard permutations of 5 avoiding [[3, 4, 1, 2], [4, 2, 3, 1]] sage: p.cardinality() 88 sage: p.random_element() [5, 1, 2, 4, 3]
︠dcdd50dc-720c-40ea-b5b9-e165efbdb23e︠