Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for Blaec (CSO) Tasks and Strategy Outline.
Download

Tutorial Release 10.4 The Sage Development Team https://doc.sagemath.org/pdf/en/tutorial/sage_tutorial.pdf

Sage is free, open-source math software that supports research and teaching in algebra, geometry, number theory, cryptography, numerical computation, and related areas. Both the Sage development model and the technology in Sage itself are distinguished by an extremely strong emphasis on openness, community, cooperation, and collaboration: we are building the car, not reinventing the wheel. The overall goal of Sage is to create a viable, free, open-source alternative to Maple, Mathematica, Magma, and MATLAB.

This tutorial is the best way to become familiar with Sage in only a few hours. You can read it in HTML or PDF versions, or from the Sage notebook (click Help, then click Tutorial to interactively work through the tutorial from within Sage).

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

https://creativecommons.org/licenses/by-sa/3.0/

386 views
ubuntu2204
Kernel: SageMath 10.4

Creating a Dictionary in Sage

Another important data structure is the dictionary (or associative array). This works like a list, except that it can be indexed with almost any object (the indices must be immutable).

from sage.all import * d = {"hi": -Integer(2), Integer(3)/Integer(8): pi, e: pi} d["hi"]
-2
d[e]
pi

You can also define new data types using classes. Encapsulating mathematical objects with classes is a powerful technique that can help to simplify and organize your Sage programs. Below, we define a class that represents the list of even positive integers up to nn; it derives from the builtin type list.

class Evens(list): def __init__(self, n): self.n = n list.__init__(self, range(2, n+1, 2))

The __init__ method is called to initialize the object when it is created; the __repr__ method prints the object out.

def __repr__(self): return "Even positive numbers up to n."

We call the list constructor method in the second line of the __init__ method. We create an object of class Evens as follows:

class Evens(list): def __init__(self, n): self.n = n list.__init__(self, range(Integer(2), n + Integer(1), Integer(2))) def __repr__(self): return "Even positive numbers up to n." e = Evens(Integer(10)) e
Even positive numbers up to n.

Note that ee prints using the __repr__ method that we defined. To see the underlying list of numbers, use the list function:

list(e)
[2, 4, 6, 8, 10]

We can also access the nn attribute or treat ee like a list.

e.n
10
e[Integer(2)]
6