{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Lecture 3: Python Core and NumPy" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Contact persons\n", "- If you experience any problem with the course\n", "- Please turn to\n", " - the lectures, examiner, or \n", " - the **course representatives**\n", "- Will hold two meetings on the course" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# Lecture 3: Python Core and NumPy\n", "- strings `str`\n", "- printing `print`\n", "- files `open` and `with`\n", "- NumPy\n", "- **Computer Assignment 1**\n", "\n", "Reading material:\n", "- [1] Sec. 2.4, 2.5.3 & 7.1 - 7.4\n", "- [2] Sec. 3.1.2, chapter 7\n", "- [4] Data types and array creation from the NumPy user manual" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Strings\n", "- Creating strings `str(...)`, `'...'`, `\"...\"`, `\"\"\"...\"\"\"`, `'''...'''`, etc.\n", "- String methods\n", "- String formatting `'...'.format(...)`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Making strings\n", "- Strings are _immutable_.\n", "- Strings can use both single `'...'` and double quotes `\"...\"` as delimiters\n", "- This makes it possible to have double `\"` or single `'` quotes in a string\n", "- Special characters can also be \"escaped\" using slash, i.e. `'\\''`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "print('Single \"quoted\" string.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Double 'quoted' string.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('This let\\'s us escape characters.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Multi-line strings\n", "Use triple quotes `\"\"\"...\"\"\"` or `'''...'''` to construct multi-line strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "print('''This is\n", "a multi-\n", "line string''')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"\"\"This is\n", "another multi-\n", "line string\"\"\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Indexing and slicing\n", "Individual characters are accessed by indexing `string[idx]`\n", "- starting from `0` from the left, and \n", "- starting from `-1` from the right\n", "\n", "For slices, `string[start:end:step]`\n", "- the `start` index is *inclusive*, \n", "- the `end` index is *exclusive*, i.e. the interval is `[start,end)`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "e = \"Another example string\"\n", "print(e[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(e[-3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(e[8:15])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(e[14:7:-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(e[-14:-6])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## String methods\n", "There are many string methods available:\n", "- `.startswith(prefix[, start[, end]]) -> bool`\n", "- `.endswith(suffix[, start[, end]]) -> bool`\n", "- `.find(sub[, start[, end]]) -> int`\n", "- `.lower() -> str`\n", "- `.upper() -> str`\n", "- `.replace(old, new[, count]) -> str`\n", "- `.split(sep=None, maxsplit=-1) -> list of strings`\n", "- `.strip([chars]) -> str`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## String methods: Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = 'This is a test string!'\n", "print(s.startswith(\"This\"), s.endswith(\"string\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(s.upper(), s.lower())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(s.replace(\"string\",\"list\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Remember strings are immutable and a **new** string is always returned when \"modifying\" a string!*" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Using `help` (and `dir`)\n", "- To see all methods of an object use `dir()`.\n", "- To get the method documentation use `help()`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(', '.join(s for s in dir(str()) if '__' not in s))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "help(str().split)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## String method `.split()`\n", "\n", "When parsing text\n", "- for splitting a string in parts, use the `.split()` method\n", "\n", "For example, \n", "- lets say you have the string `\"Blue, Green, Red, Yellow, Black\"` \n", "- and want to have the individual parts (colours) in a list of strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = \"Blue, Green, Red, Yellow, Black\"\n", "split_text = text.split(sep=', ')\n", "print(split_text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can of course use any character to split on. (Also look at `rsplit()`)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## String method `.format()`\n", "- Strings can be used to provide a formatted view of some data using the **format()** method" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'1: Hello {}, do you like {} tea?'.format( \"John\", \"green\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'2: Hello {0}, do you like {1} tea? I like {1} tea!'.format( \"John\", \"green\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'3: Hello {1}, do you like {0} tea?'.format( \"John\", \"green\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'4: Hello {0[0]}, do you like {0[1][2]} tea?'.format([\"John\", [\"black\", \"red\", \"green\"]])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'5: Hello {name}, do you like {color} tea?'.format(color=\"green\", name=\"John\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Printing with `print`\n", "- Printing is by default done to the file `sys.stdout`, but can be re-directed to (other) files as well.\n", "- Here is the full syntax for the Python 3 `print` command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "help(print)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## `print` examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(1, 2, 3, 4, 5, sep=':')\n", "print(\"First output\", end=\" | \")\n", "print(\"Second output\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Formatted `print`\n", "There are two basic methods for formatting output in Python\n", "- The old syntax from earlier versions of Python *(not recommended)*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print( \"My integer is: %d, my float is %4.3f\" % (42, 3.141592653589793) )" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- or the string formatting `.format()` method in Python 3 **(recommended)**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print( \"My integer is: {}, my float is {:4.3f}\".format(42, 3.141592653589793) )" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Python 3 format specifier syntax\n", "The format specifier (the part after the **:** inside the brackets) have this syntax:\n", "\n", "```python\n", "format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n", "fill ::= \n", "align ::= \"<\" | \">\" | \"=\" | \"^\"\n", "sign ::= \"+\" | \"-\" | \" \"\n", "width ::= integer\n", "precision ::= integer\n", "type ::= \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n", "```\n", "\n", "For full information on the *str.format* formats, see https://docs.python.org/3/library/string.html#format-string-syntax\n", "\n", "See also the nice focused guide with examples: https://pyformat.info/" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Format-strings in Python >= 3.6\n", "Python 3.6 introduced a shorter means of formatting output:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 3\n", "b = 2.5\n", "print(f\"a is equal to {a} and b is equal to {b}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here the \"f\" before the initial quote marks it as a _format_ string." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Files\n", "- All input and output go through files (almost)\n", "- The screen and keyboard are handled using the *default* files `sys.stdout` and `sys.stdin`\n", "- `sys.stdout` and `sys.stdin` are available automatically (no explicit open needed)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Files: How to?\n", "- To open a file, use the `open()` function:
`file = open(filename, mode)`\n", "* Typical `mode`s are \n", " - `\"r\"` for reading from a file, \n", " - `\"w\"` for writing to a file and \n", " - `\"a\"` to append to an existing file\n", "* After processing a file, it should be closed using the `close()` method\n", "* See `help(open)` for details" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "help(open)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## File examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = \"\"\"Hear hear!\n", "This string will be saved to file for all eternity.\n", "To read or not to read that is the question.\"\"\"\n", "\n", "with open('test_file.txt', mode='w') as file:\n", " file.write(text)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file.txt', mode='r') as file:\n", " new_text = file.read()\n", " \n", "print(new_text)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Using `with` instead of `file.close()`\n", "- Calling the `file.close()` method is not needed when using the `with` statement\n", "- It automatically calls `del file` at the end of the scope
\n", " (this is equivalent to `file.close()` for files)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "file = open('test_file.txt', mode='r')\n", "print(file.read())\n", "file.close() # I always forget to add this..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file.txt', mode='r') as file:\n", " print(file.read())\n", "# Here the file is automagically closed, nothing to forget! :D" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## More on reading from files\n", "- You can read full lines or streams of characters from a file:\n", " - `.readline()` - reads a full line (from a text file)\n", " - `.read(n)` - reads $n$ (or all remaning if $< n$) characters from the file\n", "- Or you can iterate on the file object itself!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The following two examples does exactly the same thing:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file.txt', 'r') as file:\n", " line = file.readline()\n", " while line:\n", " print(line)\n", " line = file.readline()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "with open('test_file.txt', 'r') as file:\n", " for line in file:\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "*Note that:* While the input-file had no empty lines, there are empty lines in the output.\n", "- Due to the text containing linebreaks `\\n` and \n", "- `print` adds a linebreak by default, i.e. \n", "- `print(text)` is equal to `print(text, end='\\n')`\n", "\n", "To avoid this\n", "- use one of the `strip()` or `rstrip()` string methods\n", "- or set `end=''`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "with open('test_file.txt', 'r') as file:\n", " for line in file:\n", " print(line.rstrip())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file.txt', 'r') as file:\n", " for line in file:\n", " print(line, end='')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## A word on `.read()` and `.readlines()`\n", "- The `.read()` method reads the entire file, while\n", "- the `readlines()` method reads the entire file in to a list of strings\n", "- this is strongly discouraged\n", "- large files lead to high memory usage (and a slower code)\n", "- It is much better to process files in chunks" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Writing to files `.write()`\n", "* To write, simply use the `.write()` method\n", "* Note that newlines have to be inserted explicitly!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file_2.txt', mode='w') as file:\n", " file.write('Hello .write() world!\\n')\n", " file.write('Bye bye!\\n') " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file_2.txt', mode='r') as file:\n", " for line in file:\n", " print(line, end='')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Writing to files using `print`\n", "- An alternative to `.write()` is `print()`\n", "- `print()` can be redirected from `sys.stdout` to a file" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file_2.txt', mode='w') as file:\n", " print('Hello print() world!', file=file)\n", " print('Bye bye!', file=file)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('test_file_2.txt', mode='r') as file: print(file.read())" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Python modules" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Libraries are called **packages** in Python.\n", "- [The Python Standard Library](https://docs.python.org/3/library/) is great!\n", "- But what makes Python fantastic are all the external packages\n", "- Pyhon modules are distributed using the [Python Package Index](https://pypi.python.org/pypi)
\n", " (currently listing some 200'000 modules)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- The [Anaconda Python Distribution](https://www.anaconda.com/distribution/) contanis many standard \"extra\" packages, like\n", " - NumPy, SciPy, Matplotlib, PyQT, etc." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Package structure" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A Python package are made up of a directory and file hierarchy\n", "- Each directory is also a *module* (*namespace*) in Python\n", "- Consider the NumPy package\n", " - it has the main module `numpy` and \n", " - e.g. the submodule `numpy.linalg`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "print(dir(np))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "print(dir(np.linalg))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Package directory structure\n", "That the sub-module structure corresponds to folders we can see by\n", "- printing the module filename `.__file__`, or\n", "- looking at the [NumPy source code](https://github.com/numpy/numpy/tree/master/numpy)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.linalg.__file__)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## High quality packages are well documented\n", "- Usually there are web page versions of the documentation, and\n", "- also the good old `help` function is useful" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "help(np.zeros)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# NumPy" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# NumPy\n", "is the fundamental package for scientific computing with Python. \n", "\n", "It contains among other things:\n", "- a powerful N-dimensional array object\n", "- sophisticated (broadcasting) functions\n", "- tools for integrating C/C++ and Fortran code\n", "- useful linear algebra, Fourier transform, and random number capabilities\n", "\n", "(source https://numpy.org/)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Documentation:\n", "- [The NumPy User Guide](http://docs.scipy.org/doc/numpy/user)\n", "- [The NumPy Reference Guide](http://docs.scipy.org/doc/numpy/reference)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Why NumPy?\n", "### Python `list`\n", "- Python misses a good built in data type for numerics (better than `list`)\n", "- unlike Matlab, the Python `list` type keeps *references* to objects instead of the data itself\n", "- this makes the Python `list` **very flexible**, but it also gives\n", "- poor performance and a large(r) memory footprint for multi-dimensional arrays" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### NumPy `ndarray`\n", "- The multi-dimensional array type `ndarray` in NumPy, on the other hand,\n", "- **stores data** directly in its array object\n", "- The data is stored **continuous in memory**, which further improve performance\n", "\n", "Quite a few other external libraries (like SciPy) expects data in NumPy format
to give good performace, or to work at all!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Python `list`: Element-wise operations\n", "- Multiplying objects in two lists are not allowed for `list`\n", "- Multiplication has to be done \"element by element\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = [1, 3, 4]\n", "b = [3, 2, 5]\n", "c = a * b + 1 # Multiply each element and add 1, Does _not_ work!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c = []\n", "for A, B in zip(a, b):\n", " C = A * B + 1\n", " c.append(C)\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## NumPy `ndarray`: Element-wise operations\n", "- The `ndarray` support elementwise operations (similar to Matlab)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "a = np.array([1, 3, 4])\n", "b = np.array([3, 2, 5])\n", "print(type(a), type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c = a * b + 1 # Multiply each element in a and b and add 1\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## On the NumPy `ndarray` type and element `dtypes`\n", "- The `ndarray` is the most prominent NumPy data-type \n", "- `ndarray` stands for **N**-**D**imensional **Array**\n", "- All elements in the array are of the same type (set by the `dtype` argument)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Supported `dtypes` include\n", " - `int8`, `int16`, `int32`, `int64`,
(`int == int64 or int32` depending on your platform)\n", " - `uint8`, `uint16`, `uint32`, `uint64`\n", " - `float16`, `float32`, `float64`, (`float == float64`)\n", " - `complex64`, `complex128`, (`complex == complex128`)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Array construction methods use `float` by default\n", "- Methods taking one argument use the input type to determine the return type\n", "- In operations with more than one data-type, automatic type promotion is performed" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Type promotion example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "a = np.array([1, 3, 4])\n", "b = np.array([3, 2, 5], dtype=np.int8)\n", "c = a * b + 1\n", "print(c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(type(c))\n", "print(type(c[0]))\n", "print(c.dtype)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the example above, we created a NumPy array from a Python list.\n", "\n", "This is one way of creating a NumPy array, more will be shown later." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## The `shape` of an `ndarray`\n", "\n", "- the `ndarray` can have any number of dimensions\n", "- each dimension has a fixed size\n", "- the sizes of all dimensions is called the `shape` of the array\n", "- the `shape` of an array is a `tuple`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = np.array([\n", " [1., 3.],\n", " [2., 7.],\n", " [.4, 6.],\n", " ])\n", "a.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(a)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Array creation\n", "- Create empty arrays using a shape-`tuple`\n", "- Interesting NumPy methods: `np.zeros()`, `np.ones()`, and `np.empty()`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "shape = (2, 4)\n", "a = np.zeros(shape, dtype=int)\n", "b = np.ones(shape, dtype=complex)\n", "c = np.empty(shape, dtype=float)\n", "print(a)\n", "print(b)\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note:** `np.empty` gives non-initialized arrays (fast), but they have an **undefined inital value**." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Equispaced ranges `np.arange`\n", "- To create a series of equally spaced numbers
\n", " use `np.arange(start=0, stop, step=1)`\n", "- **Note:** like for slicing, `start` is *inclusive*, `stop` is *exclusive*\n", "- Works both for `int` and `float`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = np.arange(3)\n", "b = np.arange(stop=10, start=24, step=-2)\n", "f = np.arange(1., 3., 0.2)\n", "print(\"a =\", a)\n", "print(\"b =\", b)\n", "print(\"f =\", f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- When you want to control the **number** of points (rather than the **step**)
\n", " use `np.linspace(start, stop, num=10)`\n", "- **Note:** Here both ends are *inclusive*!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c = np.linspace(-1., 1., num=9)\n", "print(\"c =\", c)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Computer Assignment 1" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# Computer Assignment 1 (CA1)\n", "\n", "The best way to learn a new language (computer or other) is of course to use it!\n", "\n", "In the Computer Assignments you will have plenty of opportunity to practice, please try to do as much as possible in your group.\n", "\n", "In **CA1** you will be able to show your skills in:\n", "* Basic Python language elements\n", "* Writing your own functions\n", "* Reading files\n", "* Storing and using data in NumPy arrays\n", "* Using Matplotlib to plot 2D data\n", "* Finding and using algorithms in SciPy" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Lecture contents\n", "* Lectures 1-3 should be enough to get you started and to finish **Step 1**\n", "* Lecture 4 we will go through material for **Step 2** and **Step 3**\n", "* Lecture 5 will introduce the SciPy package used in the last part of **Step 3**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Groups\n", "\n", "The computer assignments should be performed in groups of two.\n", "- Find another student and join one of the pre-created groups on the DAT171 Canvas page\n", "- If you can not find a group partner \n", " 1. email the examiner,\n", " 2. disclose your program (M, E, PhD,..), and \n", " 3. any schedule clashes with lectures and computer labs\n", "- If you do none of the above, you will be assigned a group on Thursday 30/1\n", "\n", "Please, form groups on your own, whenever possible.\n", "\n", "Read through the \"General instructions for the computer asignments\" and
the entire CA1 description (all the three steps) before starting to code." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Deadline for CA1 is Sunday 9/2, 2020! (actually 07.00h Monday moorning)\n", "\n", "## Good luck!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Lecture 3: The End" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import antigravity" ] } ], "metadata": { "anaconda-cloud": {}, "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 1 }