{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lecture 4\n",
"\n",
"In this lecture, we will to continue to learn NumPy `array`, and we will use flow control loops to manunipulate arrays."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Review of NumPy array\n",
"`ndarray` is an arbitrary dimension set of variables of the *same type* (cf. `list` can be concatenate different types). In default, one entry of an array is a 64-bit float (a real number represented by 64 binary digit).\n",
"* Functions: `shape`, `reshape`, `arange`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# always run this cell block first\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"arr = np.array(range(10))\n",
"print(arr)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"arr[-1] # [] is used for array indexing, () is used as input of functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## For loops\n",
"\n",
"Syntax:\n",
"> for INDEX IN A SET:
\n",
"> STUFF THAT WILL BE REPEATED IN EVERY ITERATION"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## While loops\n",
"\n",
"Very clever way to repeat actions. \n",
"\n",
"Syntax:\n",
"> while CONDITION FOR DOING THE NEXT ITERATION OF THE LOOP:\n",
"
\n",
"> STUFF THAT WILL BE REPEATED IN EVERY ITERATION"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# generate lst which is a list of integers from 0 to 9 using while\n",
"# code here\n",
"n = 0 # counter\n",
"lst = [] # initialize the list\n",
"while n < 10:\n",
" lst.append(n) # the code to be executed if n < 10\n",
" n = n + 1 # increase the counter by 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: Checking for primeness\n",
"We want to write a function called `isprime` that checks if a number is prime. Returns `True` if number is prime, `False` otherwise. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def isprime(n):\n",
" # insert code here\n",
" # we check all the divisor d < n whether n % d is 0\n",
" # recall n % d is the modulo operation, \n",
" # which return the remainder of the division using divisor d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Computing the sum of 1 to 100"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# while loop version: generating an array\n",
"arr = np.empty([100], dtype = 'int')\n",
"k = 1\n",
"while k <= 100:\n",
" arr[k-1] = k\n",
" k += 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# for loop version"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Remark: Break and continue keywords\n",
"\n",
"These are keywords:\n",
"* When the `break` was called, it stopped the loop without doing the print statement underneath. \n",
"* `continue` skips the rest of the current looping of the loop but continues to loop as usual afterwards"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"### Good exercises (try by yourself):\n",
"\n",
"* Using while loops, implement the integer division function `//` as `division(a,b)`. Make sure you are doing the negative number examples correctly. \n",
"* Write a loop to print the first 100 prime numbers. \n",
"* Make a list of all the prime numbers up to 1000 (using append to add elements)\n",
"* Write a function that will return the maximum element of a list\n",
"* Write a function that will return the sum of the elements of a list\n",
"* Write a function that takes two lists, and checks to see if they have at least one common element\n",
"* Estimate pi by adding the first 1000 terms in the formula: \n",
"$$\\frac{\\pi}{4} = 1 - \\frac13 + \\frac15 - \\frac17+ \\cdots,$$ \n",
"which comes from the Taylor expansion of $\\arctan(x)$.\n",
"Write a code snippet to compare the answer to the built-in `math.pi`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Vectorization:\n",
"\n",
"Instead of iterating along the indices, we can use built-in routine to make our execution more efficient."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"arr = np.array(range(16))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"arr = arr.reshape(4,4) + 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"arr.reshape(2,2,-1) # if you put -1, it figures out what the shape should be"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"arr"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"np.reshape(arr, (2,2,-1)) # -1 means unspecified"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"np.sum(arr)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.mean(arr)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.apply_along_axis()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.apply_along_axis(np.sum, 0, arr)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"np.apply_along_axis(np.sum, 1, arr)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.sum(arr, axis=1)"
]
}
],
"metadata": {
"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.2"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": true,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}