diff --git a/Notebook1_Wilson_Barrera.ipynb b/Notebook1_Wilson_Barrera.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f51d04c2ecf758f0fd47588d702d5a81ec879dcb --- /dev/null +++ b/Notebook1_Wilson_Barrera.ipynb @@ -0,0 +1 @@ +{"cells":[{"cell_type":"markdown","metadata":{"id":"h6xUw6cmzrmb"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-uis-student/raw/master/imgs/banner_IA.png\" width=\"1000px\" height=\"250px\">\n","\n","\n","# <center> **01. Python review! </center>**\n","\n","\n","\n","\n","## **Outline**\n","1. [**Python and data types**](#eje1)\n","2. [**Data structures**](#eje2)\n","3. [**Functions**](#eje3)\n","\n","\n"]},{"cell_type":"code","execution_count":5,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":36},"id":"uGA8zIoa_GTp","outputId":"8550d607-b34b-469e-f44f-b85200113008","cellView":"form","executionInfo":{"status":"ok","timestamp":1710722315232,"user_tz":360,"elapsed":207,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"execute_result","data":{"text/plain":["\"\\nPut your student ID here\\n\\nExample: student_id = '2152145'\\n\""],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":5}],"source":["#@title Execute this cell\n","#@markdown Please include your student id\n","import sys\n","import inspect\n","\n","group_id = \"DA-20241-Laconga\" #@param {type:\"string\"}\n","assignment_id = group_id +'.python'\n","student_id = \"2904109\" #@param {type:\"string\"}\n","\"\"\"\n","Put your student ID here\n","\n","Example: student_id = '2152145'\n","\"\"\""]},{"cell_type":"code","execution_count":7,"metadata":{"id":"nFpT39v4_GH5","executionInfo":{"status":"ok","timestamp":1710722319285,"user_tz":360,"elapsed":176,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[],"source":["#@title **Execute this cell**\n","#@markdown **UTILS**\n","#@markdown Please dont modify any line in this cell\n","\n","import os\n","import json\n","import requests\n","from collections import namedtuple\n","\n","\n","Config = namedtuple('Config', ['server_name'])\n","config = Config(server_name='https://bivlabgrader.azurewebsites.net/api')\n","\n","\n","def check_solution_and_evaluate(assignment_id: str, student_func_str: str):\n","\n"," # Set the endpoint and payload.\n"," payload = {\n"," 'func_str': student_func_str,\n"," 'assignment_id': assignment_id,\n"," 'student_id': student_id\n"," }\n"," endpoint_url = config.server_name + '/CheckAndEvaluateSolution'\n"," # print(endpoint_url)\n","\n"," # Make request to server with the data coming from the notebook.\n"," r = requests.post(endpoint_url, params=payload)\n"," pprint_json_response(r.json())\n"," return r\n","\n","\n","def pprint_json_response(response, indent=0):\n"," \"\"\"Pretty print the response.\"\"\"\n"," for key, value in response.items():\n"," print('\\t' * indent + str(key.capitalize()))\n","\n"," # If dictionary, do a recurrent call.\n"," if isinstance(value, dict):\n"," pprint_json_response(value, indent + 1)\n"," else:\n"," # Enumerate elements if list.\n"," if isinstance(value, list):\n"," if len(value) == 1:\n"," print('\\t' * (indent + 1) + str(value[0]))\n"," else:\n"," for i, e in enumerate(value, start=1):\n"," print('\\t' * (indent + 1) + f'{i}. {e}')\n"," else:\n"," print('\\t' * (indent + 1) + str(value))"]},{"cell_type":"markdown","metadata":{"id":"wgX6eHK-zrmw"},"source":["\n","#**1. Python and data types** <a name=\"eje1\"></a>\n","\n","\n","\n","\n","Image Source: www.javatpoint.com\n","\n","\n","1. **Python** is a high-level, dynamically typed multiparadigm and general-purpose programming language. The main use in this course is for scientific computing, allowing a powerful environment and the use of some popular libraries are numpy, scipy and matplotlib\n","2. **Jupyter notebook** is a web based application to create and share dynamic documents with code, equations, text and visualization.\n","3. **Numpy** is a scientific library that provides a high-performance multidimensional array object, and tools for working with these arrays\n","\n","\n","### **Basic types and operations: an automatic assignation**\n","\n"," Python has a number of basic types including integers (int), floats (float), booleans (bool), and strings (str) and even complex number representations (complex). In python the variable declaration is **not** explicit, the interpreter try to infer the type according to the use.\n","\n"," ### **1.1 Numbers**"]},{"cell_type":"code","execution_count":8,"metadata":{"id":"QM5wxQIhBUQA","colab":{"base_uri":"https://localhost:8080/"},"outputId":"81b82e57-ff6d-4aa2-939f-1b11a072846b","executionInfo":{"status":"ok","timestamp":1710722320929,"user_tz":360,"elapsed":212,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Type of x: <class 'int'>\n","Type of y: <class 'float'>\n","\n","Form 1-Sum: 5\n","Form 2-Sum: 6\n","\n","Multiplication: 12\n","\n","Exponentiation(**): 144\n","\n","Modular(%): 0\n"]}],"source":["#@title **code** Run and analyze code lines\n","x = 4\n","print(\"Type of x: \", type(x))\n","\n","y = 4.0\n","print(\"Type of y: \", type(y))\n","\n","x = x + 1\n","print(\"\\nForm 1-Sum: \", x)\n","\n","x += 1\n","print(\"Form 2-Sum: \", x)\n","\n","x *= 2\n","print(\"\\nMultiplication: \", x)\n","\n","print(\"\\nExponentiation(**): \", x**2)\n","print(\"\\nModular(%):\", x%12)"]},{"cell_type":"markdown","metadata":{"id":"Wkdd7AyzByBA"},"source":["### **1.2 Booleans**\n","\n","**Important!**\n","\n","- Python does not have unary increment (x++) or decrement (x--) operators\n","- Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.)"]},{"cell_type":"code","execution_count":9,"metadata":{"cellView":"form","id":"Fv9Pw9mNB8fI","colab":{"base_uri":"https://localhost:8080/"},"outputId":"acafb503-05bc-4947-c5a8-ee65cc05828d","executionInfo":{"status":"ok","timestamp":1710722321572,"user_tz":360,"elapsed":4,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Type of t: <class 'bool'>\n","Type of f: <class 'bool'> \n","\n","Logical AND: False\n","Logical OR: True\n","Logical NOT: False\n","Logical XOR: True\n"]}],"source":["#@title **code** Run and analyze code\n","t = True\n","f = False\n","\n","print(\"Type of t: \", type(t))\n","print(\"Type of f: \", type(f), \"\\n\")\n","\n","print(\"Logical AND: \", t and f)\n","print(\"Logical OR: \", t or f)\n","print(\"Logical NOT: \", not t)\n","print(\"Logical XOR: \", t != f)"]},{"cell_type":"markdown","metadata":{"id":"Xk9a8KgMzrnN"},"source":["**Important!**\n","\n","- Python does not have unary increment (x++) or decrement (x--) operators\n","- Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.)"]},{"cell_type":"code","execution_count":10,"metadata":{"id":"sXz3x7h4CRoH","colab":{"base_uri":"https://localhost:8080/"},"outputId":"0a5a7b59-54a6-48f3-ebba-2d1a0ee9fc6f","executionInfo":{"status":"ok","timestamp":1710722322424,"user_tz":360,"elapsed":6,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["False\n","True\n","True\n","False\n","True\n","False\n","True\n","False\n"]}],"source":["#@title **code:** Logic operators\n","\n","# Equal to\n","print(100 == 1)\n","\n","# Less than and greater than\n","print(100 >= 1)\n","print(5 < 10)\n","\n","#string equivalences\n","print('Intro to Python' == 'intro to python')\n","print('Intro to Python' == 'Intro to Python')\n","\n","# more expressions\n","print(100 == 100 and 50 == 100)\n","print(100 == 100 or 50 == 100)\n","\n","# others\n","print(not 1 == 1)"]},{"cell_type":"markdown","metadata":{"id":"OXjovAHtC-pS"},"source":["### **1.3 Strings**\n","String can be defined with single quotes or double quoutes"]},{"cell_type":"code","execution_count":11,"metadata":{"id":"E--ws909DO8N","colab":{"base_uri":"https://localhost:8080/"},"outputId":"c82ff879-89e2-4854-b687-e908c23b285d","executionInfo":{"status":"ok","timestamp":1710722322665,"user_tz":360,"elapsed":2,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Length of word_1: 11 (It include spaces and points)\n","Length of word_2: 11\n","\n","Concatenation within a and b: My name is ....\n","\n","Form 1. Concatenation within string and int: My age is 20\n","Form 2. Concatenation within string and int: My age is 20\n"]}],"source":["#@title **code** Run and analyze\n","word_1 = 'hello world'\n","word_2 = \"hello world\"\n","\n","print(\"Length of word_1: \", len(word_1), \" (It include spaces and points)\")\n","print(\"Length of word_2: \", len(word_2))\n","\n","# concatenation: we have to use \"+\" within strings\n","a = \"My name\"\n","b = \"is ....\"\n","c = a + \" \" + b\n","print(\"\\nConcatenation within a and b: \", c)\n","\n","\"\"\"\n","Concatenation within string and int\n","\"\"\"\n","a = \"My age is\"\n","b = 20\n","\n","# Form 1\n","c = a + \" \" + str(b)\n","print(\"\\nForm 1. Concatenation within string and int: \",c)\n","\n","#Form 2\n","c = '%s %d' % (a, b)\n","print(\"Form 2. Concatenation within string and int: \", c)"]},{"cell_type":"code","execution_count":12,"metadata":{"id":"ZjnjaBKLDcwv","colab":{"base_uri":"https://localhost:8080/"},"outputId":"c32693cd-cc4e-4bb2-a083-688bd448c65b","executionInfo":{"status":"ok","timestamp":1710722322915,"user_tz":360,"elapsed":2,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Split: ['hello', 'world']\n","Upper: HELLO WORLD\n","Change word: hello people\n"]}],"source":["#@title **code** Test other methods\n","#@markdown The principal [string methods](https://www.w3schools.com/python/python_ref_string.asp) are:\n","print(\"Split: \", word_1.split(' ')) # Split the word as of parameter\n","print(\"Upper: \", word_1.upper()) # Convert a string to uppercase\n","\n","word = word_1.replace('world', 'people')\n","print(\"Change word: \", word)"]},{"cell_type":"markdown","metadata":{"id":"vuwUlHlFD0Kv"},"source":["#**2. Data structures** <a name=\"eje2\"></a>\n","\n","Python includes several built-in container types: lists, dictionaries, sets, and tuples. At A.I, these structures are one of the most important issues that allows to manipulate **DATA**.\n"]},{"cell_type":"markdown","metadata":{"id":"XyxSdwZpzrna"},"source":["## **2.1 Lists**\n","\n","List are **resizeable arrays** that also can have **different element** types.\n"]},{"cell_type":"code","execution_count":13,"metadata":{"id":"Q9eZFvcFzrnc","colab":{"base_uri":"https://localhost:8080/"},"outputId":"55b90db7-c31b-4fd2-decc-fee856fb1cd1","executionInfo":{"status":"ok","timestamp":1710722323664,"user_tz":360,"elapsed":2,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["List of numbers: [1, 2, 3, 4, 5, 6, 7]\n","List of days: ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']\n","Mixed list: ['Mon', 1, 'Tue', 2, 'Wed', 3]\n","\n","-------------------------- \n","Elements of number's list: \n","\n","First element: 1 \n","Last element: 7\n","\n","Append new element: [1, 2, 3, 4, 5, 6, 7, 7]\n","Delete last element: [1, 2, 3, 4, 5, 6, 7]\n"]}],"source":["#@title **code** working with **Lists**\n","numbers = [1, 2, 3, 4, 5, 6, 7]\n","days = ['Mon', 'Tue', 'Wed', 'Thur','Fri', 'Sat', 'Sun']\n","mixed_list = ['Mon', 1, 'Tue', 2, 'Wed', 3]\n","\n","print(\"List of numbers: \", numbers)\n","print(\"List of days: \", days)\n","print(\"Mixed list: \", mixed_list)\n","\n","print(\"\\n-------------------------- \\nElements of number's list: \")\n","print(\"\\nFirst element:\", numbers[0], \"\\nLast element: \", numbers[-1])\n","\n","numbers.append(7)\n","print(\"\\nAppend new element: \", numbers)\n","\n","numbers.pop()\n","print(\"Delete last element:\", numbers)"]},{"cell_type":"markdown","metadata":{"id":"keOnsSIpFQ_9"},"source":["**List comprehension**\n","\n","Normally, you would use the following code to create a list that stores the square values:"]},{"cell_type":"code","execution_count":14,"metadata":{"id":"3l0FrAKSFZmv","colab":{"base_uri":"https://localhost:8080/"},"outputId":"50f1cab6-dae2-4b3a-faec-fcae5c3ad1ce","executionInfo":{"status":"ok","timestamp":1710722324141,"user_tz":360,"elapsed":6,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 1, 4, 9, 16]\n"]}],"source":["#@title **Code** classically\n","\n","nums = [0, 1, 2, 3, 4]\n","squares = []\n","for x in nums:\n"," squares.append(x ** 2)\n","print(squares)"]},{"cell_type":"code","execution_count":15,"metadata":{"id":"GtbOVGh-FZMz","colab":{"base_uri":"https://localhost:8080/"},"outputId":"2c789cee-0d3d-4fe3-b6b0-95e895bd5e39","executionInfo":{"status":"ok","timestamp":1710722324413,"user_tz":360,"elapsed":5,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 1, 4, 9, 16]\n"]}],"source":["#@title **code**\n","#@markdown but with list comprehension ...\n","nums = [0, 1, 2, 3, 4]\n","squares = [x ** 2 for x in nums]\n","print(squares)"]},{"cell_type":"code","execution_count":16,"metadata":{"id":"s1U1v6-CGCbm","colab":{"base_uri":"https://localhost:8080/"},"outputId":"341eca66-8b77-4619-e433-89dca1691b8b","executionInfo":{"status":"ok","timestamp":1710722324414,"user_tz":360,"elapsed":5,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Even\n"]}],"source":["#@title **code** if-else conditions in one line\n","num = 40\n","answer = 'Even' if num % 2 == 0 else 'Odd'\n","print(answer)"]},{"cell_type":"markdown","metadata":{"id":"QXn74Jamzrno"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-2-uis-student/-/raw/master/imgs/icon1.png\" width=\"200\">\n","\n","- What is `range` in python?\n","- Create a `List` with `range` that have even numbers from 100 until 500.\n","\n","```\n","[100, 102, 104, ..., 500]\n","```\n"]},{"cell_type":"code","execution_count":17,"metadata":{"id":"vcDh3dmnWGRa","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722325038,"user_tz":360,"elapsed":4,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"04e6266c-fef6-44ee-d020-ce389d22156f"},"outputs":[{"output_type":"stream","name":"stdout","text":["[100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312, 314, 316, 318, 320, 322, 324, 326, 328, 330, 332, 334, 336, 338, 340, 342, 344, 346, 348, 350, 352, 354, 356, 358, 360, 362, 364, 366, 368, 370, 372, 374, 376, 378, 380, 382, 384, 386, 388, 390, 392, 394, 396, 398, 400, 402, 404, 406, 408, 410, 412, 414, 416, 418, 420, 422, 424, 426, 428, 430, 432, 434, 436, 438, 440, 442, 444, 446, 448, 450, 452, 454, 456, 458, 460, 462, 464, 466, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 488, 490, 492, 494, 496, 498, 500]\n"]}],"source":["def even_numbers_range():\n","\n"," rango=list(range(100,501,2))\n","\n"," return rango\n","\n","print(even_numbers_range())"]},{"cell_type":"code","execution_count":18,"metadata":{"id":"yX9B0cjEWTUD","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722327911,"user_tz":360,"elapsed":2876,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"1be32b5d-36b1-459b-fb92-fa93d476aa6c"},"outputs":[{"output_type":"stream","name":"stdout","text":["Score\n","\t5\n","Message\n","\tWell done. You got the highest score.\n","Status\n","\tYou have achieved your best score: 5\n"]}],"source":["#@title **send your answer**\n","student_func_str = inspect.getsource(even_numbers_range)\n","r = check_solution_and_evaluate(assignment_id, student_func_str)"]},{"cell_type":"code","source":[],"metadata":{"id":"uJKXsZFqCK1t","executionInfo":{"status":"ok","timestamp":1710722327912,"user_tz":360,"elapsed":6,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"execution_count":18,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"eM4UJZykW9JC"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-2-uis-student/-/raw/master/imgs/icon1.png\" width=\"200\">\n","\n","- Given the lists a and b check which of the elements in index `i` is greater and append in a new list `c`.\n","\n","\n","```\n","a = [7, 5, 1, 2, 3]\n","b = [9, 4, 7, 6, 0]\n","\n","a[0] = 7\n","b[0] = 9\n","\n","c[0] = 9\n","```\n"]},{"cell_type":"code","execution_count":19,"metadata":{"id":"RrHRYXAhXHua","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722327912,"user_tz":360,"elapsed":5,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"c1207c9d-634c-4518-ff1c-4cb41d68c00f"},"outputs":[{"output_type":"stream","name":"stdout","text":["[9, 5, 7, 6, 3]\n"]}],"source":["def greater_number_list(a,b):\n"," c=[]\n"," for i in range(len(a)):\n"," c.append(a[i] if a[i]> b[i] else b[i])\n","\n"," return c\n","\n","a = [7, 5, 1, 2, 3]\n","b = [9, 4, 7, 6, 0]\n","\n","print(greater_number_list(a,b))"]},{"cell_type":"code","source":[],"metadata":{"id":"qyKo-6v5FSws","executionInfo":{"status":"ok","timestamp":1710722327912,"user_tz":360,"elapsed":3,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"execution_count":19,"outputs":[]},{"cell_type":"code","execution_count":20,"metadata":{"id":"4VhwxwKLXHpb","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722330562,"user_tz":360,"elapsed":2653,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"de503f21-0d2a-4dd5-9e8c-68147869f0dd"},"outputs":[{"output_type":"stream","name":"stdout","text":["Score\n","\t5\n","Message\n","\tWell done. You got the highest score.\n","Status\n","\tYou have achieved your best score: 5\n"]}],"source":["#@title **send your answer**\n","student_func_str = inspect.getsource(greater_number_list)\n","r = check_solution_and_evaluate(assignment_id, student_func_str)"]},{"cell_type":"markdown","metadata":{"id":"HhCb44SRYIPR"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-2-uis-student/-/raw/master/imgs/icon1.png\" width=\"200\">\n","\n","- Define a variable of string `phrase` that contains `Artificial Intelligence`.\n","- Create list `letters` that append in a loop each letter present in the `phrase`\n","- Don't append the spaces in the `phrase`"]},{"cell_type":"code","execution_count":21,"metadata":{"id":"0z6wmNuGXHnG","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722330562,"user_tz":360,"elapsed":2,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"2f7de2a9-858e-420b-a1bc-d76490de7cef"},"outputs":[{"output_type":"stream","name":"stdout","text":["['A', 'r', 't', 'i', 'f', 'i', 'c', 'i', 'a', 'l', 'I', 'n', 't', 'e', 'l', 'l', 'i', 'g', 'e', 'n', 'c', 'e']\n"]}],"source":["def string_list():\n"," phrase=\"Artificial Intelligence\"\n"," letters=[]\n"," for i in range(len(phrase)):\n"," if( phrase[i] != ' '):\n"," letters.append(phrase[i])\n"," return letters\n","print(string_list())"]},{"cell_type":"code","execution_count":22,"metadata":{"id":"f9l_-gdhXHiL","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333035,"user_tz":360,"elapsed":2474,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"34a2134b-948b-4553-db56-e1e5d8e2225b"},"outputs":[{"output_type":"stream","name":"stdout","text":["Score\n","\t5\n","Message\n","\tWell done. You got the highest score.\n","Status\n","\tYou have achieved your best score: 5\n"]}],"source":["#@title **send your answer**\n","student_func_str = inspect.getsource(string_list)\n","r = check_solution_and_evaluate(assignment_id, student_func_str)"]},{"cell_type":"markdown","metadata":{"id":"nFoEu9wzbRRv"},"source":["## **2.2 Loops**\n","\n","In Python, you can iterate a list of different ways. This depend on what you want to do."]},{"cell_type":"code","execution_count":23,"metadata":{"id":"eR8CO3_EXHfy","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333035,"user_tz":360,"elapsed":3,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"aa8958b6-1684-4e1e-daab-21848fac76c8"},"outputs":[{"output_type":"stream","name":"stdout","text":["Value: cat\n","Value: dog\n","Value: monkey\n"]}],"source":["#@title **code** option one\n","animals = ['cat', 'dog', 'monkey']\n","for animal in animals:\n"," print(\"Value: \", animal)"]},{"cell_type":"code","execution_count":24,"metadata":{"id":"Xj_0tpUEbWsg","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333226,"user_tz":360,"elapsed":9,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"6a51912b-5525-4a96-93cb-b7c3a12244e1"},"outputs":[{"output_type":"stream","name":"stdout","text":["Index: 0 Value: cat\n","Index: 1 Value: dog\n","Index: 2 Value: monkey\n"]}],"source":["#@title **code** option two\n","animals = ['cat', 'dog', 'monkey']\n","for i, animal in enumerate(animals):\n"," print(\"Index: \", i, \" Value: \", animal)"]},{"cell_type":"code","execution_count":25,"metadata":{"id":"bXWzhmanbcqx","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333227,"user_tz":360,"elapsed":9,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"f40b07a3-2772-48b4-f7cb-c1c5aefe6941"},"outputs":[{"output_type":"stream","name":"stdout","text":["Index: 0 Value: cat\n","Index: 1 Value: dog\n","Index: 2 Value: monkey\n"]}],"source":["#@title **code** option three\n","animals = ['cat', 'dog', 'monkey']\n","for animal in range(len(animals)):\n"," print(\"Index: \", animal, \" Value: \", animals[animal])"]},{"cell_type":"markdown","metadata":{"id":"X39ZokZCRcnW"},"source":["## **2.3 Dictionaries**\n","\n","The dictionaries are **special lists** like `hashes` in Java that index according to `(key, value)` pairs"]},{"cell_type":"code","execution_count":26,"metadata":{"id":"syNQ4JEIR4w6","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333227,"user_tz":360,"elapsed":8,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"9f8fb3e2-f880-4d3a-9029-1acd31e5bc97"},"outputs":[{"output_type":"stream","name":"stdout","text":["Dictionary of animals:\t {'cat': 'cute', 'dog': 'furry'}\n","Keys of dictionary:\t dict_keys(['cat', 'dog'])\n","Values of dictionary:\t dict_values(['cute', 'furry'])\n","\n","Access to a specific key, in this case, cat: cute\n","\n","Is cat in dictionary d?\t True\n","Is bird in dictionary d? False\n","\n","New element in dictionary:\t {'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}\n","Remove an element in dictionary: {'cat': 'cute', 'dog': 'furry'}\n"]}],"source":["#@title **Code** working with **Dictionaries**\n","\n","d = {'cat': 'cute', 'dog': 'furry'}\n","\n","print(\"Dictionary of animals:\\t\", d)\n","print(\"Keys of dictionary:\\t\", d.keys())\n","print(\"Values of dictionary:\\t\", d.values())\n","\n","print(\"\\nAccess to a specific key, in this case, cat: \", d['cat'])\n","\n","# Check if a dictionary has a given key\n","value = 'cat' in d\n","print(\"\\nIs cat in dictionary d?\\t\", value )\n","\n","value = 'bird' in d\n","print(\"Is bird in dictionary d?\", value )\n","\n","# Set an entry in a dictionary\n","d['fish'] = 'wet'\n","print(\"\\nNew element in dictionary:\\t\", d)\n","\n","# Remove an element from a dictionary\n","del d['fish']\n","print(\"Remove an element in dictionary:\", d)\n"]},{"cell_type":"code","execution_count":27,"metadata":{"id":"ciVlfngDb9B_","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333227,"user_tz":360,"elapsed":8,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"0f76d244-b5ed-4a6c-8924-0091b747af1f"},"outputs":[{"output_type":"stream","name":"stdout","text":["A person has 2 legs\n","A cat has 4 legs\n","A spider has 8 legs\n","A person has 2 legs\n","A cat has 4 legs\n","A spider has 8 legs\n"]}],"source":["#@title **code** operate with dictionaries\n","\n","#create a dictionary with keys and values of different types\n","d = {'person': 2, 'cat': 4, 'spider': 8}\n","\n","#Loops\n","for animal, legs in d.items():\n"," print('A %s has %d legs' % (animal, legs))\n","#Loops\n","for key in d.keys():\n"," print('A ', key, 'has ', d[key], 'legs')"]},{"cell_type":"markdown","metadata":{"id":"ybttfF2mcPF4"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-2-uis-student/-/raw/master/imgs/icon1.png\" width=\"200\">\n","\n","- The dictionary `d` contains as key `names` and `ages`of different persons.\n","- You have to extract the respective name and age and construct a string with this information.\n","- Append the string in a list and return it.\n","\n","```\n","Theodore has 18 years\n","```"]},{"cell_type":"code","execution_count":28,"metadata":{"id":"WDFSzHIHcTVn","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722333227,"user_tz":360,"elapsed":5,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"f80fd800-60fa-4330-8f92-42a8d24d7220"},"outputs":[{"output_type":"stream","name":"stdout","text":["['Theodore is 18 years old', 'Mathew is 22 years old', 'David is 30 years old']\n"]}],"source":["def names_and_ages():\n"," phrase=[]\n"," d = {'name': ['Theodore', 'Mathew', 'David'], 'age': [18, 22, 30]}\n","\n"," nombres=d[\"name\"]\n"," edades=d[\"age\"]\n","\n"," for i in range(len(nombres)):\n"," nombre=nombres[i]\n"," edad=edades[i]\n"," union=nombre + \" is \"+ str(edad) +\" years old\"\n"," phrase.append(union)\n","\n"," return phrase\n","\n","print(names_and_ages())"]},{"cell_type":"code","execution_count":29,"metadata":{"id":"Jta8LT_McV-o","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722335878,"user_tz":360,"elapsed":2653,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"be27fa99-1801-4790-ff6e-ff0d272e29a9"},"outputs":[{"output_type":"stream","name":"stdout","text":["Score\n","\t5\n","Message\n","\tWell done. You got the highest score.\n","Status\n","\tYou have achieved your best score: 5\n"]}],"source":["#@title **send your answer**\n","student_func_str = inspect.getsource(names_and_ages)\n","r = check_solution_and_evaluate(assignment_id, student_func_str)"]},{"cell_type":"markdown","metadata":{"id":"UGddh2-USxgP"},"source":["# **3 Functions** <a name=\"eje3\"></a>\n","\n","The functions are totally flexible:\n","- The type of function arguments is not declared.\n","- structured through **indentation**, i.e. code blocks are defined by their indentation\n","- The implementation should be prepared to works with the data types required !\n","- If we initiallize arguments, the functions work as **overload methods**\n","- They can return several values"]},{"cell_type":"code","execution_count":30,"metadata":{"id":"InFLgLbrTX4G","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722335878,"user_tz":360,"elapsed":3,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"17ff2206-8471-436e-e552-67fff4f4b708"},"outputs":[{"output_type":"stream","name":"stdout","text":["9\n","81\n","12\n","81\n","12\n","(16, 8)\n","(64, 12)\n","(64, 64)\n","power1 64 power2 256\n"]}],"source":["#@title **Code** working with **Functions**\n","\n","# Functions and overload methods\n","def f_power(x, p=2):\n"," return x**p\n","\n","\n","print(f_power(x=3))\n","print(f_power(p=4, x=3))\n","\n","\n","# Return several values\n","def f_power(x, p=2):\n"," return x**p, x*p\n","\n","r = f_power(p=4, x=3)\n","print(r[1])\n","\n","r1, r2 = f_power(p=4, x=3)\n","print(r1)\n","print(r2)\n","\n","# More examples\n","def f_powers(x, p1=2, p2=3):\n"," return x**p1, x**p2\n","\n","print(f_power(4))\n","print(f_power(4,3))\n","print(f_powers(4, p1=3))\n","xp1, xp2 = f_powers(4, p2=4, p1=3)\n","print(\"power1\",xp1, \"power2\", xp2)\n","\n"]},{"cell_type":"markdown","metadata":{"id":"wflgF2pvdLIF"},"source":["<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-2-uis-student/-/raw/master/imgs/icon1.png\" width=\"200\">\n","\n","- The function `math` receives as parameter the values of `a` and `b`, which are the operands. On the other hand, it receives the `operation` to be performed.\n","- With these parameters, the code must perform the operation indicated by the user, and return the result.\n","- The operations allowed are: addition, subtraction, division, multiplication and power."]},{"cell_type":"code","execution_count":31,"metadata":{"id":"m_1GRoa4dnu2","executionInfo":{"status":"ok","timestamp":1710722335878,"user_tz":360,"elapsed":2,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}}},"outputs":[],"source":["def math(a, b, operation):\n","\n"," if operation=='addition':\n"," c=a+b\n"," elif operation=='subtraction':\n"," c=a-b\n"," elif operation=='division':\n"," c=a/b\n"," elif operation=='multiplication':\n"," c=a*b\n"," elif operation=='power':\n"," c=a**b\n","\n"," return c\n","\n"]},{"cell_type":"code","execution_count":32,"metadata":{"id":"EtoYqgB6d7r3","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1710722339762,"user_tz":360,"elapsed":2627,"user":{"displayName":"wilson barrera","userId":"01747619629524347623"}},"outputId":"c9d70c1e-c4be-4322-8cba-a5f7f34627bf"},"outputs":[{"output_type":"stream","name":"stdout","text":["Score\n","\t5\n","Message\n","\tWell done. You got the highest score.\n","Status\n","\tYou have achieved your best score: 5\n"]}],"source":["#@title **send your answer**\n","student_func_str = inspect.getsource(math)\n","r = check_solution_and_evaluate(assignment_id, student_func_str)"]},{"cell_type":"markdown","metadata":{"id":"WKWsJZiazrul"},"source":["## **About markdown please see the notebook complement 01**\n","\n"]},{"cell_type":"markdown","metadata":{"id":"YCSA87eLzrvO"},"source":["## **Referencias**\n","\n","[1] [official numpy tutorial](https://docs.scipy.org/doc/numpy/user/quickstart.html)\n","\n","[2] [Datacamp tutorial of numpy](https://www.datacamp.com/community/tutorials/python-numpy-tutorial)\n","\n","[3] [Other tutorial](https://www.twilio.com/blog/2017/10/basic-statistics-python-numpy-jupyter-notebook.html)\n","\n","[4] [About dictionaries](https://docs.python.org/3.5/library/stdtypes.html#dict)\n","\n","[5] [Mathematical functions in numpy](https://docs.scipy.org/doc/numpy/reference/routines.math.html)\n","\n","[6] [More deeply in numpy](https://docs.scipy.org/doc/numpy/reference/)\n","\n","[7] [Array programming with NumPy. Nature](https://www.nature.com/articles/s41586-020-2649-2)"]},{"cell_type":"markdown","metadata":{"id":"jRcLU8qvzrvT"},"source":["---\n","<img src=\"https://gitlab.com/bivl2ab/academico/cursos-uis/ai/ai-uis-student/raw/master/imgs/bannerThanks.jpg\" alt=\"Drawing\" style=\"width:700px;\">\n"]}],"metadata":{"colab":{"collapsed_sections":["WKWsJZiazrul"],"provenance":[]},"kernelspec":{"display_name":"Python 3","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.8.8"},"toc":{"toc_cell":false,"toc_number_sections":true,"toc_threshold":6,"toc_window_display":false}},"nbformat":4,"nbformat_minor":0} \ No newline at end of file