︠6e11599f-bb59-42e7-a47f-070e629fd627i︠ %html

Introduction to Python

using sage


Sage + Python = Awesomeness

︡b17d1334-337e-4313-8e79-35f857abe459︡{"done":true,"html":"

\n

Introduction to Python

\n

using sage

\n
\n Sage + Python = Awesomeness\n

"} ︠0e9cdf84-07ff-4de8-872e-9d373aa15218i︠ %html

First things first:

Tabbing & Questions

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

︡625eb40e-7a0b-4286-9e81-e0e23985e1ee︡{"done":true,"html":"

First things first:

\n

Tabbing & Questions

\n

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

"} ︠b03a3efe-e4de-4522-9333-881ba9453d63i︠ %html

Try typing:

fibonacci?
︡c16f3f6c-7f89-420f-9a5f-5d6ee0d64762︡{"done":true,"html":"

Try typing:

\n
fibonacci?
"} ︠675ed3bb-0b85-4124-9614-91584951d4d7︠ # Try it here! fibonacci? ︡bdf6f8f5-12c3-43e7-8030-5f9530bb3c5e︡{"done":true}︡ ︠db660e26-ce48-4a09-adab-1c220c9da531i︠ %html

Second:

Data Types

Luckily there are a finite number of data types in Python. This list includes 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.

Full details can be found in the python docs. ︡76fdfb58-f683-4df7-94f0-2e3b4a723d45︡{"done":true,"html":"

Second:

\n

Data Types

\nLuckily there are a finite number of data types in Python. This list includes\n\n\nPython 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
\nFull details can be found in the python docs."} ︠f8d498f4-36ba-464c-8d8e-1c9a06625595s︠ a = "123" type(a) a = 123 type(a) ︡3b158e96-b22b-46e8-af6d-61d1cc621518︡{"stdout":"\n"}︡{"stdout":"\n"}︡{"done":true}︡ ︠cbad0a89-e8b4-426e-a203-4f39776c6366s︠ isinstance(a, Integer) isinstance(a, str) ︡19931635-c393-4526-b61b-3475303ebf9d︡{"stdout":"True\n"}︡{"stdout":"False\n"}︡{"done":true}︡ ︠05d01a38-4b29-426d-8482-f83cf0c32086i︠ %html

Booleans

bool has one of two values: True and False.

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

You can convert something into a boolean by the bool function.

︡b2ee09b5-d479-4b67-8b32-bdc98629ceae︡{"done":true,"html":"

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

"} ︠460f0aeb-f9d7-482a-9aed-448de63196fds︠ type(True) ︡1d0cbfff-15fb-4483-8a86-7037fbd86cf6︡{"stdout":"\n"}︡{"done":true}︡ ︠71d848b0-77eb-4e24-afb3-0cb7cd417198s︠ bool(1) bool(0) bool(-1) ︡7962e245-cb2f-4fdd-b002-92159895afcb︡{"stdout":"True\n"}︡{"stdout":"False\n"}︡{"stdout":"True\n"}︡{"done":true}︡ ︠76192771-ab83-4d4e-acec-fd1838756ea1s︠ True and False ︡011b427d-2fdb-460b-84fa-c2bf6e90b45f︡{"stdout":"False\n"}︡{"done":true}︡ ︠446127bb-a1be-4152-a086-9bde53b52aa6s︠ not True ︡5ecbe17c-87b4-4ff5-964c-13f952b3e63f︡{"stdout":"False\n"}︡{"done":true}︡ ︠0bf73127-11b6-442a-b1af-b4152ee6232as︠ False or True ︡e2cf0745-c366-4179-8102-d738b6b09c57︡{"stdout":"True\n"}︡{"done":true}︡ ︠4a44f9d5-f570-457c-8e34-beffaede2486i︠ %html

Integers/Floats

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

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

︡1ab9e3c6-550f-4526-a314-126413479d9d︡{"done":true,"html":"

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

"} ︠e9924e42-1084-431e-8106-51e86a137c59s︠ int(5)/int(2) ︡109005e7-c603-4828-9e3c-b98ca5948448︡{"stdout":"2\n"}︡{"done":true}︡ ︠6d173746-37b5-43b9-8910-612afa6bc68es︠ type(1) type(1.2) ︡9e899121-e3b2-4855-b2dd-89f7d54be4bf︡{"stdout":"\n"}︡{"stdout":"\n"}︡{"done":true}︡ ︠09dda59f-9900-49b5-854f-3060baafcc72i︠ %html

Strings

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.

︡8d819b53-0adf-4616-b584-8d094604366c︡{"done":true,"html":"

\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

"} ︠e82313cb-0563-4632-bb17-d857ce81a6bbs︠ aram = 'Aram' print """Hello %s, You're a pretty cool person. - %s """ % ('human', aram) ︡e9349a30-abca-47aa-86e3-dcaeb70d9b1b︡{"stdout":"Hello human,\nYou're a pretty cool person.\n- Aram\n\n"}︡{"done":true}︡ ︠8b21002f-379c-44da-8ab1-64e23160718ass︠ print a, "factors into", a.factor() ︡4bc64b8f-b219-4674-9611-b07d61cc53d6︡{"stdout":"123 factors into 3 * 41\n"}︡{"done":true}︡ ︠e2716743-5900-40c0-a3d3-ce96462466eds︠ print str(a) + " factors into " + str(a.factor()) ︡ad88ce6c-d3f2-4aa9-8c28-9cb05d5ae7dc︡{"stdout":"123 factors into 3 * 41\n"}︡{"done":true}︡ ︠80d785a3-5597-49fe-8588-f4ba4554ce76i︠ %html

Sets, lists, tuples, and dictionaries

Because, why not.
  • set - is a set of items with no multiplicites or order.
  • list - is an ordered list of items
  • tuple - is the same as a list, but it is immutable (it cannot be changed).
  • dict - Is an associative array which associates values with keys.
︡c6639e79-77b1-44db-a7a9-30e680228a50︡{"done":true,"html":"

Sets, lists, tuples, and dictionaries

\n
Because, why not.
\n
    \n
  • set - is a set of items with no multiplicites or order.
  • \n
  • list - is an ordered list of items
  • \n
  • tuple - is the same as a list, but it is immutable (it cannot be changed).
  • \n
  • dict - Is an associative array which associates values with keys.
  • \n
"} ︠d448cdd4-fe85-48d0-b81f-f342154ae919i︠ %html

Some basic commands

Constructing stuff

︡367def72-c5bc-41c2-857e-0d409a792ce7︡{"done":true,"html":"

Some basic commands

\n

\n Constructing stuff\n

"} ︠6cf7c75d-2b96-4bab-8239-42185026ff48s︠ S = set([1,2,3]) L = [1,2,3] T = (1,2,3) D = {2:1, 3:2, 4:3} S L T D ︡e7df4c1a-367b-40ae-a6f0-d1db3311c702︡{"stdout":"set([1, 2, 3])\n"}︡{"stdout":"[1, 2, 3]\n"}︡{"stdout":"(1, 2, 3)\n"}︡{"stdout":"{2: 1, 3: 2, 4: 3}\n"}︡{"done":true}︡ ︠9cd1c57b-b990-4d4e-b85d-1a0b02279b52s︠ set([1]) [1] {1:2} ︡df625e2e-f993-4ae7-97d7-32087a99e563︡{"stdout":"set([1])\n"}︡{"stdout":"[1]\n"}︡{"stdout":"{1: 2}\n"}︡{"done":true}︡ ︠a651cdd6-0bc8-4ea7-b300-f38b2441c395s︠ (1) (1,2) ︡35a6e52f-7327-44c7-9606-5cacf9cc4c37︡{"stdout":"1\n"}︡{"stdout":"(1, 2)\n"}︡{"done":true}︡ ︠e4950c90-5090-4b04-87af-fc63f729330es︠ (1,) ︡dbadfe79-394d-4567-bd08-1564db9e108e︡{"stdout":"(1,)\n"}︡{"done":true}︡ ︠94e93079-9f43-4e22-946e-688847728fbdi︠ %html

How many stuff does it have?

Use the len function. ︡fa3f6add-986c-4a14-8a48-9ac71f59b56d︡{"done":true,"html":"

\n How many stuff does it have?\n

\nUse the len function."} ︠967a422e-7b3b-44b3-b898-167f0f877644s︠ len(S) len(L) len(T) len(D) ︡52a8e4df-e4a6-426d-9504-59755152e962︡{"stdout":"3\n"}︡{"stdout":"3\n"}︡{"stdout":"3\n"}︡{"stdout":"3\n"}︡{"done":true}︡ ︠5cb5e9f1-3b84-40e5-98c5-57b3eea083d0i︠ %html

Is this object present?

Use the in operator.
Note: The in operator for dictionaries looks at the keys! ︡8989c085-16e2-48f2-b33c-a47bd2f9af2e︡{"done":true,"html":"

\n Is this object present?\n

\n\nUse the in operator.
\nNote: The in operator for dictionaries looks at the keys!"} ︠a3ab964b-badf-4530-9a45-959097c5410ds︠ S = set([1,2,3]) L = [1,2,3] T = (1,2,3) D = {2:1, 3:2, 4:3} 1 in S 1 in L 1 in T 1 in D ︡667ede1a-87b1-405b-a053-83ca39438e9d︡{"stdout":"True\n"}︡{"stdout":"True\n"}︡{"stdout":"True\n"}︡{"stdout":"False\n"}︡{"done":true}︡ ︠e4809fe6-c0fd-491e-8f26-cae056a6b1d9s︠ 4 not in S 4 not in L 4 not in T 4 not in D ︡2a6b3737-16b8-437b-963e-9f64dc1dea68︡{"stdout":"True\n"}︡{"stdout":"True\n"}︡{"stdout":"True\n"}︡{"stdout":"False\n"}︡{"done":true}︡ ︠1651c02a-7aac-473f-94b6-19853be8a3e9i︠ %html

How do I access elements?

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. ︡40c35db4-5250-45a6-81fa-c8f0599355c2︡{"done":true,"html":"

\n How do I access elements?\n

\nUse 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."} ︠473696a5-16c8-4e6d-a887-1c60815f377cs︠ L = [1,2,3] T = (1,2,3) D = {2:1, 3:2, 4:3} L[0] T[0] D[2] ︡102295dd-1269-430a-9243-e6dc1730176f︡{"stdout":"1\n"}︡{"stdout":"1\n"}︡{"stdout":"1\n"}︡{"done":true}︡ ︠2698ab54-ae0b-4c46-9bbe-38aa656f0caci︠ %html

Can I modify things?

Only lists and dictionaries! Tuples are immutable, so they can't be altered. ︡f46e1e38-3d26-4a87-89a9-36e587650792︡{"done":true,"html":"

\n Can I modify things?\n

\nOnly lists and dictionaries! Tuples are immutable, so they can't be altered."} ︠7508ae96-18db-499a-837d-75448d5724aes︠ L[0] = 5 D[2] = 5 L D ︡b4a0a975-45a9-4f7c-a1c2-e33e48cf3c0f︡{"stdout":"[5, 2, 3]\n"}︡{"stdout":"{2: 5, 3: 2, 4: 3}\n"}︡{"done":true}︡ ︠7f484d77-9f33-4108-b7e7-77ebc157c497i︠ %html

How do I add new things?

There are many ways my young padawan.
Sets - Use the add function
Lists - You can append a list at the end, extend a list with another list, or just plain add two lists together.
Tuples - They are immutable, so we can't alter them! We can add two of them together and create a new tuple though.
Dictionaries - Just add a new key and put in a value.
︡988f7a35-a7fd-4307-bde3-f7d523330954︡{"done":true,"html":"

\n How do I add new things?\n

\nThere 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
"} ︠dd5247ac-9185-4b43-9c84-78538bd77c7cs︠ S = set([1,2,3]) S.add(2) S.add(4) S ︡c24d1559-ecb4-4a8f-908d-2495cbd8b3d2︡{"stdout":"set([1, 2, 3, 4])\n"}︡{"done":true}︡ ︠1f53ee06-0007-464c-8230-8a5cc3bdd320s︠ L = [1,2,3] L2 = ["a", "b"] L3 = [(1,2), (4,5)] L.append(4) L.extend(L2) L L4 = L2 + L3 L4 ︡6b14f080-82a3-454e-a37c-ed63e786132b︡{"stdout":"[1, 2, 3, 4, 'a', 'b']\n"}︡{"stdout":"['a', 'b', (1, 2), (4, 5)]\n"}︡{"done":true}︡ ︠e46d39f8-8224-4573-a364-0f4fba956ccas︠ T = (1,2,3) T2 = (0,0) T3 = T + T2 T3 ︡1fac299a-4b66-421e-aec9-76fbf6d3e164︡{"stdout":"(1, 2, 3, 0, 0)\n"}︡{"done":true}︡ ︠7e9f037b-6ec2-4b91-aeb7-1728b73cf074s︠ D = {2:1, 3:2, 4:3} D[10] = fibonacci(10) D[(3,2,1)] = Permutation([3,2,1]) D ︡89850356-be1c-4e81-80ea-260cfeaf7810︡{"stdout":"{2: 1, 3: 2, 4: 3, 10: 55, (3, 2, 1): [3, 2, 1]}\n"}︡{"done":true}︡ ︠ed531dcd-1923-43fe-9e58-c8e009d76400i︠ %html Note: For lists we can't add additional items like we do in dictionaries. ︡f738358f-cb1a-42c7-89c9-db17a2c3f7f1︡{"done":true,"html":"Note: For lists we can't add additional items like we do in dictionaries."} ︠be6ff520-d74c-4a76-a44b-3d934e474161s︠ L[10] = fibonacci(10) ︡4fd4fdc2-863f-47b3-bcde-e7454a80947e︡{"stderr":"Error in lines 1-1\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 905, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nIndexError: list assignment index out of range\n"}︡{"done":true}︡ ︠6dcf9053-19d4-4e1c-9007-566aab867b2fi︠ %html Note: We also can't add mutable items as keys for dictionaries. ︡f6d20c88-7e55-4b58-b401-e3fecdbe3618︡{"done":true,"html":"Note: We also can't add mutable items as keys for dictionaries."} ︠b96760af-be25-4d89-b94f-72939b1f5928s︠ D[[1]] = 'fail' ︡5c36bf37-dd28-4c67-b11a-356b78d6b870︡{"stderr":"Error in lines 1-1\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 905, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nTypeError: unhashable type: 'list'\n"}︡{"done":true}︡ ︠a79655be-763f-4133-a272-5c5fcd1cc321i︠ %html

Russell's paradox

Sets of sets can't happen
︡420a4d1f-7403-465c-8585-4ead901ae009︡{"done":true,"html":"

\n Russell's paradox\n

\n
\n Sets of sets can't happen\n
"} ︠96b76308-b3a2-469e-ad0f-9d81a3deeb46s︠ S1 = set([1,2,3]) S2 = set([S1]) S2 ︡65964482-5d53-4a9f-8c25-122221d4bb3a︡{"stderr":"Error in lines 2-2\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 905, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nTypeError: unhashable type: 'set'\n"}︡{"done":true}︡ ︠963da764-c237-46f9-bb92-0f5367eda3a2s︠ S1 = frozenset([1,2,3]) S2 = set([S1]) S2 ︡2a22db94-adc9-462a-9cf4-91709cfc8955︡{"stdout":"set([frozenset([1, 2, 3])])\n"}︡{"done":true}︡ ︠c6a2a22c-ac22-4573-a65c-d11db45047fbi︠ %html Exercise: Look at the following code and make a guess as to what will be displayed. ︡d6fe3fab-8097-4469-bc0f-fc7fa52cfb92︡{"done":true,"html":"Exercise: Look at the following code and make a guess as to what will be displayed."} ︠4f07d38e-8a73-4a05-a716-3da6db0fa7a0s︠ L = [1,"z",3,4,5] L.append("c") L = L + [9,10] L[6] ︡ab233445-da70-4967-823a-f0d973850495︡{"stdout":"9\n"}︡{"done":true}︡ ︠27a1e87f-1b3e-48bb-8d94-ff8c3805980ei︠ %html

But I added too much! How do I delete things I don't want?

︡0091226d-93b2-4bd8-bccb-9d5ff3d9452b︡{"done":true,"html":"

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

"} ︠7f69192e-e0f3-4627-a72d-f7f47ff24b63ss︠ S = set([1,2,3]) S.discard(2) S ︡81d9d178-ba33-41e9-88a9-5971089b674d︡{"stdout":"set([1, 3])\n"}︡{"done":true}︡ ︠0eb67729-3cf0-446a-a004-346ff39e0f65s︠ L = [1,2,3,4,5] del L[1] poppedItem = L.pop(0) L.remove(3) L poppedItem L.remove(3) ︡5214d175-3055-4db1-9dc0-c03109e64f10︡{"stdout":"[4, 5]\n"}︡{"stdout":"1\n"}︡{"stderr":"Error in lines 7-7\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 905, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nValueError: list.remove(x): x not in list\n"}︡{"done":true}︡ ︠c31c8a9e-f50e-46d1-8ae1-03ba899af0d6s︠ L = [1, 2, 3, 2] L.remove(2) L ︡bf510e82-25d0-4462-ad00-8185f7ca0bdb︡{"stdout":"[1, 3, 2]\n"}︡{"done":true}︡ ︠4c461870-370e-459d-bec2-155618483a66s︠ L2 = [1,2,3,4,5] L2 = L2[1:3] L2 ︡a4dbbac0-02a9-4eb0-9c71-9865efea6539︡{"stdout":"[2, 3]\n"}︡{"done":true}︡ ︠f6bad326-8944-4ab8-a2f7-6dbf8f670290s︠ T = (1,2,3,4,5) T = T[1:3] T ︡f4f04eb4-8d6c-4dfb-852c-4b1a398fe0ea︡ ︠9860df18-8068-4963-8318-3ac578201c06s︠ D = {2:1, 3:2, 4:3} del D[3] poppedItem = D.pop(4) D ︡b22d306f-029c-4a96-bffe-7226dc7d0f77︡{"stdout":"{2: 1}\n"}︡{"done":true}︡ ︠0d3f073e-f27f-4870-b3f9-c8dc9d5adc28i︠ %html
Some other useful commands (Lists only!):
  • sort
  • reverse
︡31dc7b81-9476-4ba1-bd8f-3bd7b74f2b6b︡{"done":true,"html":"
\n Some other useful commands (Lists only!):\n
\n
    \n
  • sort
  • \n
  • reverse
  • \n
"} ︠2d68ef01-9dbe-41c0-85e3-648503d8fc03s︠ L = [5,4,1,2,3] L.sort() L ︡a62d24f0-579a-4fd1-b42c-f0781003ef01︡{"stdout":"[1, 2, 3, 4, 5]\n"}︡{"done":true}︡ ︠41a7a3b2-05b8-4878-aa9a-fb54a6e3e773︠ ︡5f6b15ea-3703-4b0d-bf90-c1cb3d43f5f4︡ ︠48eb6f1b-29cd-42c2-8005-fe8392ce43f1s︠ L = [5,4,1,2,3] L.reverse() L ︡6a01449a-5caf-4b44-a65d-14d32fade2c7︡{"stdout":"[3, 2, 1, 4, 5]\n"}︡{"done":true}︡ ︠d6a9c3c6-33ca-4b35-9259-9c9d90bbcd48i︠ %html

Some basic commands

Operation set list tuple dict
Construction set([]) [] () {}
One element construction set([1]) [1] (1,) {1:1}
Size len(set) len(list) len(tuple) len(dict)
Contains x in set x in list x in tuple key in dict
Accessing entries - list[0] tuple[0] dict[key]
Adding stuff set.add(x) list.append(x)
list.extend(list2)
list3 = list1 + list2
tuple3 = tuple1 + tuple2 dict[key] = x
key must be immutable
Deleting stuff set.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]
︡9f99c451-cdf7-4471-a9cc-86ac2e80b872︡{"done":true,"html":"

Some basic commands

\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]
"} ︠412b180b-e828-49c9-8018-eabb7ebeb1c6i︠ %html Exercise:
  1. Create the list [5,1,3,6,7,2,12].
  2. Remove the element 12.
  3. Add the element 4.
  4. Sort the list and reverse it.
︡4f3d6a9b-db3c-4f30-9f72-e5103b321ad1︡{"done":true,"html":"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
"} ︠9a6ba292-6865-479b-98bc-ec85f93e899c︠ # Try it out! ︡b220a64b-e07e-4c53-abc6-72c36944f3f2︡ ︠e0e4f341-f592-46e6-9b75-8a48af2a15d6i︠ %html

The modification problem.

Or things that should be illegal.
Changing lists and dictionaries can have unintended consequences. ︡2498f3d2-e771-4bc4-aa2d-914faa8b6e93︡{"done":true,"html":"

\n The modification problem.\n

\n
\n Or things that should be illegal.\n
\nChanging lists and dictionaries can have unintended consequences."} ︠e0b35070-7fb6-49f3-b9b6-e4fa2830bb82s︠ L = ["a", "b", "c"] L2 = [L, L] L2 ︡8374c55e-6605-4112-9b8a-a8b37af88ffa︡{"stdout":"[['a', 'b', 'c'], ['a', 'b', 'c']]\n"}︡{"done":true}︡ ︠d07ecc4d-add7-4135-ac50-60b25930b0e2s︠ L.append("d") L2 ︡7ac7111c-49c0-42d1-9556-0d992f017bd7︡{"stdout":"[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]\n"}︡{"done":true}︡ ︠2cd873ab-4efc-4ce9-bfd3-6b7adf4fa21ds︠ L = ["a", "b", "c"] L2 ︡2160aa79-e5eb-4c3f-9a58-df84b40a4e28︡{"stdout":"[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]\n"}︡{"done":true}︡ ︠686e3d1e-e58f-418a-88fa-6e5be9da8e11s︠ L2[0].remove("c") L2 ︡fe394fa9-99db-4c5d-8c9b-d90797d30488︡{"stdout":"[['a', 'b', 'd'], ['a', 'b', 'd']]\n"}︡{"done":true}︡ ︠948d2a61-98f0-44ba-b7f5-7d569ef09f08i︠ %html

Stop this nonsense! How do we fix this?

deepcopy to the rescue!

︡fc1a3029-b45a-4090-87c5-9b9356771653︡{"done":true,"html":"

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

\n

\n deepcopy to the rescue!\n

"} ︠82815d43-cb4c-44a6-b164-cc89b9d335ebs︠ L = ["a", "b", "c"] L2 = [deepcopy(L), deepcopy(L)] L2 ︡4355817a-54f0-40e3-be1d-ec7690ccdc22︡{"stdout":"[['a', 'b', 'c'], ['a', 'b', 'c']]\n"}︡{"done":true}︡ ︠051549da-8968-4efb-a7f3-08e35100d57fs︠ L.append("d") L2 ︡e3051b7e-0fd4-4d33-8223-751e3f773ef5︡{"stdout":"[['a', 'b', 'c'], ['a', 'b', 'c']]\n"}︡{"done":true}︡ ︠81395411-69a0-4657-b545-786fc37007a7i︠ %html

The None type

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

︡537fc1f9-6a81-44bd-8a73-15a90d3f3026︡{"done":true,"html":"

\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

"} ︠80faa48a-5d6b-47ba-97f9-3cd108774b12s︠ v = None v ︡6b1777a3-54af-4ee3-bd4a-699b8e3ed043︡{"done":true}︡ ︠c873a2bd-3f88-4721-ba15-ceab71d9428bi︠ %html

Ranges

Lists made easy

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

︡97c92072-e8b7-4004-be8c-e0efcd02dd26︡{"done":true,"html":"

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

"} ︠e0c4cb2b-910e-4816-a2f8-0882b5294261s︠ range? ︡6a161932-f8f7-4304-af26-90ccc646b59e︡{"code":{"filename":null,"lineno":-1,"mode":"text/x-rst","source":"File: \nDocstring :\nrange(stop) -> list of integers range(start, stop[, step]) -> list of\nintegers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement). For\nexample, range(4) returns [0, 1, 2, 3]. The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements."}}︡{"done":true}︡ ︠96e00d78-cce4-4b9f-ba4c-f4253674a70cs︠ range(1,10) ︡c96a05f7-0fa5-43d2-8a20-c567a12a6492︡{"stdout":"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}︡{"done":true}︡ ︠8096e392-b458-4be7-b041-e637f7a3a27es︠ range(1,10,2) ︡36e75bce-1a7d-404f-acba-58cef72f41d8︡{"stdout":"[1, 3, 5, 7, 9]\n"}︡{"done":true}︡ ︠8b298316-ccc1-4cc8-8d98-6569b40ddeads︠ range(20,1,-1) ︡bbd29314-d481-473f-a374-9eb3b5637f4b︡{"stdout":"[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]\n"}︡{"done":true}︡ ︠318ea4f2-a764-485a-a0bc-cebb3986919ei︠ %html Exercise: Use range to construct the list of even numbers between $1$ and $40$ (including $40$).
Bonus: Put it in reverse order. ︡f5639df7-1801-4aed-a449-71b3b0fdd419︡{"done":true,"html":"Exercise: Use range to construct the list of even numbers between $1$ and $40$ (including $40$).
\nBonus: Put it in reverse order."} ︠cd841134-6dc8-40e9-bf31-697ee615a63bs︠ # Try it out! range(2,41,2) range(40,1,-2) ︡6265881e-c029-4c19-af0f-d3bf5b1fe81e︡{"stdout":"[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]\n"}︡{"stdout":"[40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]\n"}︡{"done":true}︡ ︠0ff37a08-bf4b-48bf-b187-16acdc7e2019i︠ %html

Third parts the charm:

Control Flows

  • if - Does something if the condition is true.
  • for - Loops through a range of objects.
  • while - Keeps looping until condition is false.
For more details you can visit the control flow page on the Python docs. ︡4292fa19-a443-47b8-a7a8-41b7f3f8c0ff︡{"done":true,"html":"

Third parts the charm:

\n

Control Flows

\n
    \n
  • if - Does something if the condition is true.
  • \n
  • for - Loops through a range of objects.
  • \n
  • while - Keeps looping until condition is false.
  • \n
\n\nFor more details you can visit the control flow page on the Python docs."} ︠158cf406-9c1c-4211-9dbc-7d2ff6f508b7i︠ %html

Quick aside: Comparisons

  • or    and    not - Boolean operators
  • == - Equal
  • != - Not equal
  • <   >   <=   >= - Inequalities
  • is - Object identity
  • is not - Negated object identity
︡f4cd5983-338a-4593-a864-8f0ef85e7f8d︡{"done":true,"html":"

\n Quick aside: Comparisons\n

\n
    \n
  • or    and    not - Boolean operators
  • \n
  • == - Equal
  • \n
  • != - Not equal
  • \n
  • <   >   <=   >= - Inequalities
  • \n
  • is - Object identity
  • \n
  • is not - Negated object identity
  • \n
"} ︠2d57448c-6c4c-4979-b506-75c1fb747b71i︠ %html

if

with its siblings elif and else.
︡bd203f29-b592-44b0-b5a0-e9fff2b4cc7a︡{"done":true,"html":"

\n if\n

\n
\n with its siblings elif and else.\n
"} ︠b339d952-01bb-4d39-8e28-bb6075d65e8es︠ if 2 in (1,2,3,4): print "2 is in our tuple!" ︡c01af4e5-3460-4a76-8e08-acd961a428cd︡{"stdout":"2 is in our tuple!\n"}︡{"done":true}︡ ︠9fdfab85-093f-426a-99b0-e4738e43d4f1s︠ R = range(1,10,2) if 2 in R: print "2 is in range." elif 4 in R: print "4 is in range." else: print "By faulty induction our range is only odd numbers." ︡6174e741-62a3-4963-8f24-4d0e0b9330c3︡{"stdout":"By faulty induction our range is only odd numbers.\n"}︡{"done":true}︡ ︠75e4df11-344b-49ad-bd67-4076b1e2b2bci︠ %html

for

︡4c479fb4-1533-4a7e-a276-907536ed4c31︡{"done":true,"html":"

\n for\n

"} ︠6bb509c9-9ac0-421f-ac77-1910a1dd2980s︠ for i in set([3,2,1]): print i ︡4663e3d6-74e4-4c55-bb35-b26ddf024908︡{"stdout":"1\n2\n3\n"}︡{"done":true}︡ ︠c43ac8b7-5d85-456a-a50f-e8d5c50c9e73s︠ for i in range(1,5): print i ︡6cfb6afe-6dc0-4d4c-9094-bb778cb7dc0b︡{"stdout":"1\n2\n3\n4\n"}︡{"done":true}︡ ︠36d87217-6d21-4353-8301-5280d35961a6s︠ for i in range(1,10): if i % 2 == 0: print i ︡411fed68-d506-46ee-a3ae-69303b287b68︡{"stdout":"2\n4\n6\n8\n"}︡{"done":true}︡ ︠13c31b9b-d81f-470e-af9d-5ee21a533542s︠ for i in range(1,10): if is_prime(i): print i ︡1e3df216-e314-4dff-b478-d30ea1264f60︡{"stdout":"2\n3\n5\n7\n"}︡{"done":true}︡ ︠81ea5897-8526-491e-8063-ef1642f7f2c2i︠ %html Exercise: Use a for loop to print out all the non-even primes from $1$ to $100$. ︡8286882b-cdd4-4894-adbf-e0f54fdb9bbd︡{"done":true,"html":"Exercise: Use a for loop to print out all the non-even primes from $1$ to $100$."} ︠3af781b6-0615-4ce0-83d1-a06166262686s︠ # Try it yourself for i in range(1,100): if is_prime(i) and i % 2 != 0: print i ︡d8285ce7-ce8c-4bd0-b22c-ef8a5323ecdc︡{"stdout":"3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n53\n59\n61\n67\n71\n73\n79\n83\n89\n97\n"}︡{"done":true}︡ ︠68fe8b8e-8c7d-4daf-b880-729779f94f93i︠ %html

while

︡1d8ddad8-105c-4031-9703-3ea46ebcc844︡{"done":true,"html":"

\n while\n

"} ︠95b54ce1-bbbd-4e68-a660-9bd61b10946es︠ C = 3 while C != 1: print C if C % 2 == 0: C /= 2 else: C = C*3 + 1 ︡91547c31-828f-4751-8b18-9a317f146ea9︡{"stdout":"3\n10\n5\n16\n8\n4\n2\n"}︡{"done":true}︡ ︠b8befe99-c2c1-4258-a180-284ff1539731i︠ %html

for and list

The super team
We can use for loops in order to create super awesome lists. ︡d3cbee1e-1234-48b0-9c62-61248ddc7e66︡{"done":true,"html":"

\n for and list\n

\n
\n The super team\n
\nWe can use for loops in order to create super awesome lists."} ︠ef914f90-f2d3-4119-802b-7aa31e4c0a30s︠ [i^2 for i in range(1,10)] ︡5e7a2d9c-4b0b-4843-9447-2afb9a24914f︡{"stdout":"[1, 4, 9, 16, 25, 36, 49, 64, 81]\n"}︡{"done":true}︡ ︠fe611baf-a112-4e87-b24f-1d372e99963bi︠ %html We can even combine if statements! ︡cb8b8b1e-c3c3-489a-a707-2cc17b3ca77c︡{"done":true,"html":"We can even combine if statements!"} ︠cdc0e6bb-7d32-41e6-9d15-063bd25a12des︠ [i for i in range(1,50) if i%7 == 0 or i%5 == 0] ︡0cd03eed-5738-412f-9339-b54df5149ba0︡{"stdout":"[5, 7, 10, 14, 15, 20, 21, 25, 28, 30, 35, 40, 42, 45, 49]\n"}︡{"done":true}︡ ︠58322dcb-1137-4138-966f-6f5a56674e62i︠ %html And take sums! ︡b5538a01-693c-4203-bee5-6f71224c97d0︡{"done":true,"html":"And take sums!"} ︠b18fa781-c811-4c0c-aea4-a92461999248s︠ sum([p for p in range(1,10) if is_prime(p)]) ︡e7533239-cd5c-4519-ab22-a5fdf0cf49c5︡ ︠80fefcbe-be48-427b-a451-8d6d03e520bai︠ %html Exercise: Find the sume of the non-even primes from $1$ to $100$. ︡7840813f-8c0e-4751-938a-38cedf165782︡{"done":true,"html":"Exercise: Find the sume of the non-even primes from $1$ to $100$."} ︠4fcd0b7f-84b7-40ab-9b52-92c9080c4c98︠ # Try it yourself! ︡e47bc3f4-6c9b-4498-a3f2-58e91ab08022︡ ︠beae0550-104d-44a5-a944-37bde4f1dd30i︠ %html

Wait, it gets better.... Nesting!

We can nest these lists in order to construct lists of tuples, dictionaries, matrices, etc. ︡82ff61c3-b331-4a98-9706-6fd8a03f93cf︡{"done":true,"html":"

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

\nWe can nest these lists in order to construct lists of tuples, dictionaries, matrices, etc."} ︠c7f1e2d9-f25c-4553-b5d9-c33645ba5eebs︠ [(x,y,z) for x in range(1,3) for y in range(1,3) for z in range (1,3)] ︡c19798d9-818b-41f5-aedf-7048f0291c44︡ ︠38e716ca-ec8e-48e1-8d11-60f5310e44c3s︠ [[i^j for j in range(1,3)] for i in range(1,5)] ︡b880e6ba-ee07-4292-9b73-6af1649f0024︡ ︠c4148dec-e9e6-4d1d-b6ed-ee2b3beceec6︠ ︡601fdf43-4e9c-4092-9b81-4d599401aea1︡ ︠7475f674-64ac-4420-ad55-5164e7cf9402s︠ matrix([[i^j for j in range(1,3)] for i in range(1,5)]) ︡d37f24ad-413e-46b9-8f6c-5ce432531a6b︡ ︠fd296d75-c7da-42d5-9952-ab6297d9b785i︠ %html

These special lists also allow us to grab the keys/values of dictionaries!

︡229704dc-2f5a-4194-afc8-2e97b85d8670︡{"done":true,"html":"

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

"} ︠fdcf292c-94c8-47e7-8e73-e0ea8906730fs︠ D = {2:1, 3:2, 4:3} [value for value in D.itervalues()] ︡d5146111-faef-4712-8871-1e403bba766a︡ ︠d28a51c2-214e-41c5-85c9-bd0a5f01ae95s︠ [key for key in D.iterkeys()] ︡fd107c90-8624-4381-9056-413454c2739d︡ ︠70e55f28-b8f5-4aa9-b766-07475535eef1s︠ [(key,value) for key,value in D.iteritems()] ︡564f3cf4-2ffc-4b73-b811-69c513c899ec︡ ︠1499a03e-d01c-43a1-98e1-801e18845178i︠ %html

Integers vs ints

Revisited
︡09310eb0-2ce5-4eac-bfed-698c1557ef8e︡{"done":true,"html":"

Integers vs ints

\n
Revisited
"} ︠b3b54567-787d-4be2-baf8-7ef499baf03e︠ matrix(QQ, [[i/j for i in range(1,10)] for j in range(1,10)]) ︡b99f9565-0849-4f9a-a1d3-95f7e76a4345︡ ︠b8848356-0318-4015-b3a9-31294fee9bbd︠ matrix(QQ, [[i/j for i in srange(1,10)] for j in srange(1,10)]) ︡a928b098-6fa2-42c9-af11-321fe261f466︡ ︠a7881b01-1c60-4a4e-b12c-cb61c7b4c1a1i︠ %html

Part $2^2$:

Functions

Functions are defined using the def statement. We can return things from functions using the return keyword. ︡db7f52cd-3141-4b6f-aff0-da4e17e21e3b︡{"done":true,"html":"

\n Part $2^2$:\n

\n

\n Functions\n

\nFunctions are defined using the def statement. We can return things from functions using the return keyword."} ︠9eadf5b2-317a-4b4a-9043-14df1017a96bs︠ def f(x): return x^2 f(2) ︡f70ede9d-2b90-450c-b0da-6462fcd49b2b︡ ︠0758c4f8-9e8d-415a-aade-9453ddbc5b81i︠ %html

Recursion - Catalan Numbers

$C_0 = 1$
$C_{n} = \frac{2(2n-1)}{n+1} C_{n-1}$ ︡107e4557-526b-4926-a1fd-64c0a1474d92︡{"done":true,"html":"

\n Recursion - Catalan Numbers\n

\n$C_0 = 1$
\n$C_{n} = \\frac{2(2n-1)}{n+1} C_{n-1}$"} ︠d0948dc0-8645-4af7-8d62-1c9e4938eb53s︠ def catalanNumber(x): if x == 0: return 1 else: return (2 * (2 * x - 1) / (x+1)) * catalanNumber(x-1) [catalanNumber(n) for n in range(0,10)] ︡2ab35f5b-d700-48d6-bb69-a33e2ae04603︡ ︠0656473b-8c5a-48fe-9354-3d6d43dba3bfi︠ %html

Complicated recursion - Catalan Numbers part 2

$C_0 = 1$
$C_n = \sum_{i = 0}^{n-1} C_{i} C_{n-1-i}$ ︡d0161207-c47c-4d79-b3bd-e52fa9b0c222︡{"done":true,"html":"

\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}$"} ︠2cd8b43d-e7f7-4aaa-88f8-c2df2e400bccs︠ def catalanNumber(x): if x == 0: return 1 else: return sum([ (catalanNumber(i) * catalanNumber(x-1 - i)) for i in range(0,x)]) [catalanNumber(n) for n in range(0,10)] ︡854b5f9f-7217-4868-8440-bda014040da9︡ ︠5b79ca00-a8a5-478a-b9bd-0cadc555068ei︠ %html Exercise: Create a function for the fibonacci series and display the first $20$. ︡ac503a3e-1893-46d1-ba2e-c9504b73b4f9︡{"done":true,"html":"Exercise: Create a function for the fibonacci series and display the first $20$."} ︠059ef14d-0778-48bd-9173-cab1ce34b8d3︠ # Try it! ︡b079af0e-2242-4871-ae4d-7a01869ed122︡ ︠9191de02-9f96-47f1-bced-84e9c483a85ai︠ %html

Functions can also have default values.

︡32dc7c47-23ef-445a-bcef-66d531183dc3︡{"done":true,"html":"

\n Functions can also have default values.\n

"} ︠a25ef25d-590f-445d-97fd-95adef0f8a3fs︠ # By default we choose 1 def choose(n, k = 1): return binomial(n,k) choose(5) choose(5,2) ︡c82448c0-c11d-4aff-a08a-31e247886070︡ ︠7af4051f-2ff1-41b2-b624-1ef3a3e34ea5i︠ %html

Functions can also return multiple values if desired.

︡e9266950-7971-4368-bfb4-76da274d4b9d︡{"done":true,"html":"

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

"} ︠0ce67677-7479-483f-ad38-b924228b051as︠ def fibAndCat(n): return fibonacci(n), catalan_number(n) F, C = fibAndCat(5) F C ︡2f7b3bad-16a9-43d8-945f-7a64520082f4︡ ︠86b988c0-7ffb-42a6-9307-6ca62a627c57s︠ [fibAndCat(i) for i in range(0,10)] ︡3ba7b1c9-e785-40c5-afe8-d3579447dbf8︡ ︠44afaa96-5047-4b94-bdb2-375cf65758d5i︠ %html

Digraphs!

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.

︡2e5537b2-7d15-468d-822d-c6a710af9a6c︡{"done":true,"html":"

\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

"} ︠a9a68755-c684-4d0b-9a14-52d0d1e66440s︠ D = {0:[1,2,3], 1:[0,3], 2:[3,4], 4:[5,5,5,1], 5:[5]} G = DiGraph(D) G.plot() ︡7084e5ba-4901-427a-a1ca-f68f97961fac︡ ︠c648c01e-4e0d-4fb4-8349-029b84ed9814s︠ G.adjacency_matrix() ︡49440dd9-0d99-4cd0-9de0-8e75162e4526︡ ︠8a73d64f-c8ef-4ca2-8b2f-167800fd1961i︠ %html Exercise: Plot your favourite digraph. ︡7fbe3547-64ad-4c11-a7ba-f2744f1a80d5︡{"done":true,"html":"Exercise: Plot your favourite digraph."} ︠892d6683-179f-4c24-b251-06d270442fce︠