{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

\n", "

Introduction to Python

\n", "

using sage

\n", "
\n", " Sage + Python = Awesomeness\n", "

\n", "

\n", " This is an introduction to the basic functionality of Python and Sage, with an emphasis on seeing how to handle a worksheet and how to get more detailed help. We will point out a little bit of the power that Sage has hiding in it, but this is not a full-fledged tutorial.\n", "

\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "

Zero:

\n", "

The start of it all

\n", "

There are two (main) ways to use sage: terminal and browser.

\n", "

\n", " Terminal: You can use sagemath from your computer itself. Everything lives on your computer. Uses your computers components, so it'll be faster.

\n", "     On Ubuntu, you can type sage from your computer and it'll open up the terminal. You can then type whatever code you want and hit enter and you'll get the results.\n", "

\n", "

\n", " Browser: You can use sagemath from any website. Everything lives on the cloud (good for collaboration/sharing). Uses cocalc servers, so it'll be slower.

\n", "     This file is the browser version. We normally call these \"worksheets\" and each little box in a worksheet is a \"cell\". This is where you write you code on the browser. Once you've written your code, you type shift + enter and you'll get your results.\n", "

\n", "

\n", " Let's test out that sage works. Try doing 2+7 in sage.\n", "

\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 1, "metadata": { }, "output_type": "execute_result" } ], "source": [ "2+7" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

First things first:

\n", "

Tabbing & Questions

\n", "

If you don't know what a function does, type the function, add a ? and hit shift+enter for a quick description.

\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "

Try typing:

\n", "
fibonacci?
\n", "

\n", " and pressing shift+enter\n", "

\n", "\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it here!\n", "fibonacci?" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Congrats! For the next parts, go ahead and read the information and hit `shift+enter` each time you want to test something out.\n", "\n", "Try doing `shift+enter` on the following to test it out. (The first lines makes everything look pretty by using latex =D)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "i < 3*u" ] }, "execution_count": 1, "metadata": { }, "output_type": "execute_result" } ], "source": [ "%display latex\n", "var('x','i','u')\n", "f = (9*x - 7*i > 3 * (3*x - 7*u))\n", "3*f.solve(i)[0][0]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

Second:

\n", "

Data Types

\n", "Luckily there are a finite number of data types in Python. This list includes\n", "\n", "\n", "Python is a dynamic language, so there is no need to declare what variable type you are using. You can also change the type of your variables. To know what type a variable is you can just ask for it's type using the type function. Or you can ask directly if the object is of a certain type using isinstance.
\n", "
\n", "Full details can be found in the python docs." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Let's first set-up a string and an integer. Notice how their types are different." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "a = \"123\"\n", "print type(a)\n", "\n", "a = 123\n", "print type(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print isinstance(a, Integer)\n", "print isinstance(a, str)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

Booleans

\n", "

\n", " bool has one of two values: True and False.\n", "

\n", "

\n", " There are three boolean operators: and, or, & not.\n", "

\n", "

\n", " You can convert something into a boolean by the bool function.\n", "

\n", "

\n", " Notice in the following that True returns 'bool' as its type.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "type(True)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Notice that when converting something to boolean, we normally get True, except for when we input $0$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print bool(1)\n", "print bool(0)\n", "print bool(-1)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "In particular, the following give us False:\n", "+ The integer 0\n", "+ The string ''" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "We can also do operations on booleans using `and`, `or`, `not`, etc." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "True and False" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "True and True" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "False and False" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "not True" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "False or True" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

Integers/Floats

\n", "

\n", " int is the python built-in integer type. The problem with the python version is the integer conversion problem.\n", " Due to this restriction, Sage uses its own type called Integer.\n", "

\n", "

\n", " float is the python built-in rational number type. Due to similar restrictions, Sage uses the RealLiteral type.\n", "

\n", "\n", "Look at what happens if we force numbers to use python's integers." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "int(5)/int(2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "This is definitely not true!!!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ " In order to get around this, sage uses its own definition of integer using the integer ring." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print type(1)\n", "print type(1.2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Strings\n", "

\n", "

\n", " The str type is fairly common. You can use single or double quotes. Additionally you can use triple quotes if you want a multi-line string. You can also fill a string using dictionary substitutions as can be seen in the following example.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "aram = 'Aram'\n", "print \"\"\"Hello %s,\n", "You're a pretty cool person.\n", "- %s\n", "\"\"\" % ('human', aram)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Concatenation\n", "\n", "You can concatenate strings either using `,` or `+`. The difference is that `,` will auto-type convert and will add spaces automatically. `+` on the other hand assumes everything is a `str` variable and will not add spaces." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print a, \"factors into\", a.factor()" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print str(a) + \" factors into \" + str(a.factor())" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

Sets, lists, tuples, and dictionaries

\n", "
Because, why not.
\n", "

\n", " There are four more (complicated) types:\n", "

\n", "" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

Some basic commands

\n", "

\n", " Constructing stuff\n", "

\n", "

\n", " This is how you can construct a set, list, tuple and dict.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S = set([1,2,3])\n", "L = [1,2,3]\n", "T = (1,2,3)\n", "D = {2:1, 3:2, 4:3}\n", "\n", "print S\n", "print L\n", "print T\n", "print D" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "To have only one element in your object, it's generally normal:" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print set([1])\n", "print [1]\n", "print {1:2}" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that for tuples, you can't just have 1 element! Look at what happens if we try and define a tuple with just one element." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print (1)\n", "print (1,2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "If you reaaaaalllly want a tuple with one element, you need to add a comma after the first element to force it to be a tuple." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "(1,)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " How many stuff does it have?\n", "

\n", "Use the len function." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print len(S)\n", "print len(L)\n", "print len(T)\n", "print len(D)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Is this object present?\n", "

\n", "\n", "Use the in operator." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S = set([1,2,3])\n", "L = [1,2,3]\n", "T = (1,2,3)\n", "D = {2:1, 3:2, 4:3}\n", "\n", "print 1 in S\n", "print 1 in L\n", "print 1 in T\n", "print 1 in D" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "print 4 not in S\n", "print 4 not in L\n", "print 4 not in T\n", "print 4 not in D" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "Did you notice how for `dictionaries` the in operator is looking at the key and not the value? Remember this forever!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " How do I access elements?\n", "

\n", "Use square brackets to access individual items. For dictionaries you use the key. For lists and tuples the counting begins at $0$. Sets have no order so you can't \"access\" things." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [1,2,3]\n", "T = (1,2,3)\n", "D = {2:1, 3:2, 4:3}\n", "print L[0]\n", "print T[0]\n", "print D[2]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Can I modify things?\n", "

\n", "Only lists and dictionaries! Tuples are immutable, so they can't be altered." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L[0] = 5\n", "D[2] = 5\n", "print L\n", "print D" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " How do I add new things?\n", "

\n", "There are many ways my young padawan.\n", "
\n", " Sets - Use the add function\n", "
\n", "
\n", " Lists - You can append a list at the end, extend a list with another list, or just plain add two lists together.\n", "
\n", "
\n", " Tuples - They are immutable, so we can't alter them! We can add two of them together and create a new tuple though.\n", "
\n", "
\n", " Dictionaries - Just add a new key and put in a value.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "### `set` example for adding new things" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S = set([1,2,3])\n", "S.add(2)\n", "S.add(4)\n", "S" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "### `list` example for adding new things" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [1,2,3]\n", "L2 = [\"a\", \"b\"]\n", "L3 = [(1,2), (4,5)]\n", "\n", "L.append(4)\n", "L.extend(L2)\n", "print L\n", "L4 = L2 + L3\n", "print L4" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "### `tuple` example for adding new things\n", "\n", "Recall that since they are immutable, you can't add directly to a `tuple`" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "T = (1,2,3)\n", "T2 = (0,0)\n", "T3 = T + T2\n", "print T3" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "### `dict` example for adding new things" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "D = {2:1, 3:2, 4:3}\n", "D[10] = fibonacci(10)\n", "D[(3,2,1)] = Permutation([3,2,1])\n", "D" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Note: For lists we can't add additional items like we do in dictionaries." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L[10] = fibonacci(10)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Note: We also can't add mutable items as keys for dictionaries." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "D[[1]] = 'fail'" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Russell's paradox\n", "

\n", "
\n", " Sets of sets can't happen\n", "
" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S1 = set([1,2,3])\n", "S2 = set([S1])\n", "S2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "If you want a set of a set you need to create a `frozenset`. Frozen sets are immutable and therefore they can be placed in a set." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S1 = frozenset([1,2,3])\n", "S2 = set([S1])\n", "S2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Look at the following code and make a guess as to what will be displayed." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [1,\"z\",3,4,5]\n", "L.append(\"c\")\n", "L = L + [9,10]\n", "L[6]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " But I added too much! How do I delete things I don't want?\n", "

" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "For sets we can just discard the item we want. Note that we must `discard` the actual element and not the 'index' as indices don't exist in a set." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "S = set([1,2,3])\n", "S.discard(2)\n", "S" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "For a `list` we can either delete by index using `del`, we can `pop` an item out, or we can `remove` an item by its value.\n", "\n", "For `del` you must specify the list with the index you are trying to remove.\n", "For `pop` you specify the index as well, but unlike `del`, it will actually return the item removed so you can use it later if you want.\n", "For `remove` you specify the value of the thing you want to remove. This is useful if you don't know the index." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [1,2,3,4,5]\n", "del L[1]\n", "poppedItem = L.pop(0)\n", "L.remove(3)\n", "L" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "Note: `remove` will only remove the first time it sees an object. It won't remove all of them." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [1, 2, 3, 2]\n", "L.remove(2)\n", "L" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "You can also use splicing. Splicing won't be covered in full here, but if you're interested, here's a good article on it." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L2 = [1,2,3,4,5]\n", "L2 = L2[1:3]\n", "L2" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "T = (1,2,3,4,5)\n", "T = T[1:3]\n", "T" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "For `dict` we can do similar things as list. We can `del` or we can `pop`. Recall that we are using the keys and not the values." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "D = {2:1, 3:2, 4:3}\n", "del D[3]\n", "poppedItem = D.pop(4)\n", "D" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "
\n", " Some other useful commands (Lists only!):\n", "
\n", "" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [5,4,1,2,3]\n", "L.sort()\n", "L" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [5,4,1,2,3]\n", "L.reverse()\n", "L" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

Some basic commands

\n", "Here's a summary of everything we just talked about.\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Operationsetlisttupledict
Constructionset([])[](){}
One element constructionset([1])[1](1,){1:1}
Sizelen(set)len(list)len(tuple)len(dict)
Containsx in setx in listx in tuplekey in dict
Accessing entries - list[0]tuple[0]dict[key]
Adding stuffset.add(x)list.append(x)
list.extend(list2)
list3 = list1 + list2
tuple3 = tuple1 + tuple2dict[key] = x
key must be immutable
Deleting stuffset.discard(item)list.pop(i)
del list[i]
list = list[start:end]
list.remove(value)
tuple = tuple[start:end]dict.pop(key)
del dict[key]
" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise:\n", "
    \n", "
  1. Create the list [5,1,3,6,7,2,12].
  2. \n", "
  3. Remove the element 12.
  4. \n", "
  5. Add the element 4.
  6. \n", "
  7. Sort the list and reverse it.
  8. \n", "
" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it out!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

\n", " The modification problem.\n", "

\n", "
\n", " Or things that should be illegal.\n", "
\n", "Changing lists and dictionaries can have unintended consequences. To see this, let's start off with constructing a list.\n", "\n", "Note that for theatrical purposes, I'll have you do the heavy work of hitting `shift+enter` for each code. Try and think about what you would expect to happen each time before running the code." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [\"a\", \"b\", \"c\"]\n", "L2 = [L, L]\n", "L2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "This seems fairly normal. We have a list composed with two lists. But now watch what happens when we add an element to our list `L`." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L.append(\"d\")\n", "L2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "WHAT?! That's mental right? So what happens if we change `L` to something altogether?" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [\"a\", \"b\", \"c\"]\n", "L2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "But `L2` didn't change!\n", "\n", "So what happened? Basically variables in Python work a little differently than we might otherwise think. When creating a variable Python assigns the variable to a slot in your RAM with the data inside of it.\n", "When you then use that variable to construct other variables (such as for `L2 = [L,L]`) Python doesn't duplicate the data.\n", "Instead, it says \"create an array with two elements where the information for these elements contained in the slot where `L` is\".\n", "So in essence this new memory slot points to the original slot!\n", "Therefore when we alter `L` by appending a `d` to it, `L2` still is pointing to that memory slot and therefore will show the `d` now as well.\n", "\n", "But what happened when we reconstructed `L`?!\n", "That is because whenever we do a `=` it resets the memory slot.\n", "So now `L` is pointing to a different slot in RAM and altering it won't affect `L2` anymore.\n", "\n", "BUT that doesn't mean we can't get weird things happening still!\n", "`L[0]` is nothing more than just a pointer to the original memory slot that used to contain `L`.\n", "So what do yu think will happen when we alter this?" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L2[0].remove(\"c\")\n", "L2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Stop this nonsense! How do we fix this?\n", "

\n", "

\n", " deepcopy to the rescue!\n", "

\n", "Basically, what `deepcopy` does is makes a copy of the data instead of just pointing!\n", "Like this we won't get a lot of this alteration problems." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L = [\"a\", \"b\", \"c\"]\n", "L2 = [deepcopy(L), deepcopy(L)]\n", "L2" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "L.append(\"d\")\n", "L2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

\n", " The None type\n", "

\n", "

\n", " If you want to set a variable but don't want to set it as any particular type, you can use None\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "v = None\n", "print v" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

Ranges

\n", "
Lists made easy
\n", "

\n", " Ranges allow us to make numerical lists easily. We use the range function to construct a range.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "range?" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "If we want all the numbers between 1 and 10 we would do the following:" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "range(1,10)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that `10` is not included!\n", "This is because `range` is \"starting\" from `1` and going up to (but not including) `10`.\n", "Something to note!.\n", "\n", "Also, you can skip over every other element if we want." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "range(1,10,2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Or we can go backwards!" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "range(20,1,-1)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Use range to construct the list of even numbers between $1$ and $40$ (including $40$).
\n", "Bonus: Put it in reverse order." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it out!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

Third parts the charm:

\n", "

Control Flows

\n", "\n", "\n", "For more details you can visit the control flow page on the Python docs." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "

\n", " Quick aside: Comparisons\n", "

\n", "" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " if\n", "

\n", "
\n", " with its siblings elif and else.\n", "
\n", "\n", "An `if` statement is exactly like what it sounds like.\n", "If something is true, then do something." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "if 2 in (1,2,3,4):\n", " print \"2 is in our tuple!\"" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "If we have multiple things we can use `elif` and `else` to help.\n", "`elif` stands for \"else if\".\n", "The rest should be easy to understand." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "R = range(1,10,2)\n", "if 2 in R:\n", " print \"2 is in range.\"\n", "elif 4 in R:\n", " print \"4 is in range.\"\n", "else:\n", " print \"By faulty induction our range is only odd numbers.\"" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " for\n", "

\n", "\n", "`for` is used for constructing loops.\n", "It does \"something\" for each item in something." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "for i in set([3,2,1]):\n", " print i" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "outputs": [ ], "source": [ "for i in range(1,5):\n", " print i" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "for i in range(1,10):\n", " if i % 2 == 0:\n", " print i" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "for i in range(1,10):\n", " if is_prime(i):\n", " print i" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Use a for loop to print out all the non-even primes from $1$ to $100$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it yourself" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " while\n", "

\n", "\n", "`while` is a loop that keeps going while a certain condition is true.\n", "\n", "Note: be careful of creating infinite loops!\n", "Always make sure that your loop WILL end at some point." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "source": [ "Let's look at this through the Collatz conjecture." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "C = 3\n", "while C != 1:\n", " print C\n", " if C % 2 == 0:\n", " C /= 2\n", " else:\n", " C = C*3 + 1" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " for and list\n", "

\n", "
\n", " The super team\n", "
\n", "We can use for loops in order to create super awesome lists." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[i^2 for i in range(1,10)]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "We can even combine if statements!" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[i for i in range(1,50) if i%7 == 0 or i%5 == 0]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "And take sums!" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "sum([p for p in range(1,10) if is_prime(p)])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Find the sume of the non-even primes from $1$ to $100$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it yourself!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Wait, it gets better.... Nesting!\n", "

\n", "We can nest these lists in order to construct lists of tuples, dictionaries, matrices, etc." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[(x,y,z) for x in range(1,3) for y in range(1,3) for z in range (1,3)]" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "outputs": [ ], "source": [ "[[i^j for j in range(1,3)] for i in range(1,5)]" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "matrix([[i^j for j in range(1,3)] for i in range(1,5)])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " These special lists also allow us to grab the keys/values of dictionaries!\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "D = {2:1, 3:2, 4:3}\n", "[value for value in D.itervalues()]" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[key for key in D.iterkeys()]" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[(key,value) for key,value in D.iteritems()]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

Integers vs ints

\n", "
Revisited
\n", "\n", "So do you recall how integers in Python have a division problem?\n", "Check out this matrix...." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "matrix(QQ, [[i/j for i in range(1,10)] for j in range(1,10)])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "That looks wrong...\n", "Basically, range will return Python integers and NOT sage integers!\n", "This is obviously a problem if we actually want to work with these numbers.\n", "So, sage includes with it `srange` which is a copy of `range` but instead returns sage integers and not Python integers.\n", "Let's see this in action." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "matrix(QQ, [[i/j for i in srange(1,10)] for j in srange(1,10)])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "

\n", " Part $2^2$:\n", "

\n", "

\n", " Functions\n", "

\n", "Functions are defined using the def statement. We can return things from functions using the return keyword." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "def f(x):\n", " return x^2\n", "\n", "f(2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Recursion - Catalan Numbers\n", "

\n", "$C_0 = 1$
\n", "$C_{n} = \\frac{2(2n-1)}{n+1} C_{n-1}$" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "def catalanNumber(x):\n", " if x == 0:\n", " return 1\n", " else:\n", " return (2 * (2 * x - 1) / (x+1)) * catalanNumber(x-1)\n", "\n", "[catalanNumber(n) for n in range(0,10)]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Complicated recursion - Catalan Numbers part 2\n", "

\n", "$C_0 = 1$
\n", "$C_n = \\sum_{i = 0}^{n-1} C_{i} C_{n-1-i}$" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "def catalanNumber(x):\n", " if x == 0:\n", " return 1\n", " else:\n", " return sum([ (catalanNumber(i) * catalanNumber(x-1 - i)) for i in range(0,x)])\n", "\n", "[catalanNumber(n) for n in range(0,10)]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Create a function for the fibonacci series and display the first $20$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Try it!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Functions can also have default values.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# By default we choose 1\n", "def choose(n, k = 1):\n", " return binomial(n,k)\n", "\n", "print choose(5)\n", "print choose(5,2)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Functions can also return multiple values if desired.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "def fibAndCat(n):\n", " return fibonacci(n), catalan_number(n)\n", "\n", "F, C = fibAndCat(5)\n", "print F\n", "print C" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "[fibAndCat(i) for i in range(0,10)]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "

\n", " Digraphs!\n", "

\n", "

\n", " Sage allows us to construct digraphs using dictionaries. Let's take a sidestep and look at how to construct digraphs and some operations we can do on them.\n", "

" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "D = {0:[1,2,3], 1:[0,3], 2:[3,4], 4:[5,5,5,1], 5:[5]}\n", "G = DiGraph(D)\n", "G.plot()" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "outputs": [ ], "source": [ "G.adjacency_matrix()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "subslide" } }, "source": [ "Exercise: Plot your favourite digraph." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ ], "source": [ "# Test this out here." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "source": [ "Thanks for reading this tutorial!!!\n", "\n", "If you have any suggestions, just email me and let me know =D I'm more than happy to make this more accessible to everyone =)\n", "Also, feel free to use this for anything =)\n", "The more humans using sage the better =D\n", "\n", "**Email:** aram.dermenjian@gmail.com\n", "**Website:** dermenjian.com" ] } ], "metadata": { "kernelspec": { "argv": [ "sage-10.2", "--python", "-m", "sage.repl.ipython_kernel", "--matplotlib=inline", "-f", "{connection_file}" ], "display_name": "SageMath 10.2", "env": { }, "language": "sagemath", "metadata": { "cocalc": { "description": "Open-source mathematical software system", "priority": 2, "url": "https://www.sagemath.org/" } }, "name": "sage-10.2", "resource_dir": "/ext/jupyter/kernels/sage-10.2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.15" } }, "nbformat": 4, "nbformat_minor": 4 }