From 880b8729bd5c5dc146a6be497691227dd4d27a53 Mon Sep 17 00:00:00 2001 From: Samuel Simeone Date: Fri, 27 Aug 2021 20:27:56 -0400 Subject: [PATCH] lab_lambda_functions [Samuel Simeone] --- .../Learning-checkpoint.ipynb | 291 ++++++++++++ .../.ipynb_checkpoints/main-checkpoint.ipynb | 440 ++++++++++++++++++ your-code/Learning.ipynb | 2 +- your-code/main.ipynb | 198 ++++++-- 4 files changed, 883 insertions(+), 48 deletions(-) create mode 100644 your-code/.ipynb_checkpoints/Learning-checkpoint.ipynb create mode 100644 your-code/.ipynb_checkpoints/main-checkpoint.ipynb diff --git a/your-code/.ipynb_checkpoints/Learning-checkpoint.ipynb b/your-code/.ipynb_checkpoints/Learning-checkpoint.ipynb new file mode 100644 index 0000000..ecb174e --- /dev/null +++ b/your-code/.ipynb_checkpoints/Learning-checkpoint.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambda Functions\n", + "\n", + "\n", + "Lesson Goals\n", + "\n", + "In this lesson you will learn all about lambda (or anonymous) functions and how they are used in Python.\n", + "Introduction\n", + "\n", + "Lambda functions are also called anonymous functions. What this means is that they are functions without a name. Lambda functions are typically short expressions. They can take multiple arguments but unlike functions, they can only have one expression.\n", + "Defining a Lambda Function\n", + "\n", + "For the most part, any lambda expression can also be written as a function (but not vice versa). When writing a lambda, we typically use the syntax of declaring a lambda and then listing the inputs of the lambda followed by a colon and then the expression.\n", + "\n", + "Let's look at an example of a lambda function and an equivalent function in Python below." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "25\n", + "25\n" + ] + } + ], + "source": [ + "# Below is a lambda function that takes a number and returns its square\n", + "square = lambda x: x * x\n", + "\n", + "# Here we have a function that returns the same result as the lambda function\n", + "def square_function(x):\n", + " return x * x\n", + " \n", + "print (square(5))\n", + "print (square_function(5))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also pass multiple arguments to our lambda function." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "11" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "summarize = lambda a, b: a + b\n", + "\n", + "summarize(5, 6)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# If Statements in Lambda Functions\n", + "\n", + "If statements have a slightly different syntax in a lambda expression. Below is an example of a lambda expression that computes the fraction of two numbers unless the denominator is zero." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.5\n", + "0\n" + ] + } + ], + "source": [ + "div = lambda num, denom: num / denom if (denom != 0) else 0\n", + "\n", + "print (div(5, 10))\n", + "\n", + "print (div(10, 0))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As we can see in the lambda function above, we specify the if after we specify the action. We also do not use colons in the if statement.\n", + "\n", + "\n", + "# Lambdas in the Return Statement of a Function\n", + "\n", + "We can use lambda expressions to return a function from a function. Here is an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "range(0, 10)\n", + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "def generate_range(lower):\n", + " return lambda upper: range(lower, upper)\n", + " \n", + "custom_range = generate_range(0)\n", + "\n", + "\n", + "\n", + "print (custom_range(10)) \n", + "print ([x for x in custom_range(10)])\n", + "print ([x for x in custom_range(5)])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambdas in List Comprehensions\n", + "\n", + "Lambdas are great when we want to generate a list in a quick and concise manner. We can apply the lambda expression to every element in the list and generate a new list.\n", + "\n", + "Here is an example of generating the squares of all numbers 1 through 10. We generate the numbers using the range function and square them using a lambda expression. " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25, 36, 49, 64, 81]\n" + ] + } + ], + "source": [ + "square = lambda x: x * x\n", + "squared = [square(x) for x in range(1, 10)]\n", + "\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use lambda functions to transform existing lists. Here we replace a dash with a space in a list of school subjects." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Calculus', 'Philosophy', 'Art History', 'Computer Science']\n" + ] + } + ], + "source": [ + "school_dash = ['Calculus', 'Philosophy', 'Art-History', 'Computer-Science']\n", + "\n", + "school_space = [(lambda x: x.replace('-', ' '))(x) for x in school_dash]\n", + "\n", + "print(school_space)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambdas as Arguments in Functions\n", + "\n", + "Lambda functions really shine as arguments in functions. One example is sorting. Typically, we only sort using the default options in Python. However, we can define our own custom sorting lambda expression and pass that as an argument to the sorting function.\n", + "\n", + "In the example below we will sort by the last letter of the school subject. We will first create a lambda function that returns the last letter of the string and then sort using this function as a sorting key." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Computer Science', 'Calculus', 'Philosophy', 'Art History']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "last = lambda x: x[-1]\n", + "\n", + "sorted(school_space, key=last)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As we can see, we sorted by the last letter of each string.\n", + "Advantages and Disadvantages of Lambda Functions\n", + "\n", + "Lambda functions have several advantages but also some disadvantages.\n", + "\n", + "Advantages:\n", + "\n", + " Lambda functions are concise since they only contain one expression.\n", + " Lambda can be passed around without a variable (hence why they are considered anonymous).\n", + " Lambda functions return automatically.\n", + "\n", + "Disadvantages:\n", + "\n", + " Sometimes lambda functions can over-complicate and it would be better to use a regular function instead. Particularly, when the expression is complex and may benefit from being separated into multiple lines.\n", + " They use different syntax (for example, if statements have different syntax in lambda functions).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/your-code/.ipynb_checkpoints/main-checkpoint.ipynb b/your-code/.ipynb_checkpoints/main-checkpoint.ipynb new file mode 100644 index 0000000..d35df0a --- /dev/null +++ b/your-code/.ipynb_checkpoints/main-checkpoint.ipynb @@ -0,0 +1,440 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Before your start:\n", + "- Read the README.md file\n", + "- Comment as much as you can and use the resources in the README.md file\n", + "- Happy learning!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 1 - Passing a Lambda Expression to a Function\n", + "\n", + "In the next excercise you will create a function that returns a lambda expression. Create a function called `modify_list`. The function takes two arguments, a list and a lambda expression. The function iterates through the list and applies the lambda expression to every element in the list." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Follow the steps as stated below:\n", + " 1. Define a list of any 10 numbers\n", + " 2. Define a simple lambda expression for eg that updates a number by 2\n", + " 3. Define an empty list\n", + " 4. Define the function -> use the lambda function to append the empty list\n", + " 5. Call the function with list and lambda expression\n", + " 6. print the updated list " + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n" + ] + } + ], + "source": [ + "l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", + "f = lambda x: x + 5\n", + "b = []\n", + "\n", + "def modify_list(lst, fudduLambda):\n", + " for x in lst:\n", + " b.append(fudduLambda(x))\n", + " \n", + "modify_list(l, f)\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Now we will define a lambda expression that will transform the elements of the list. \n", + "\n", + "In the cell below, create a lambda expression that converts Celsius to Kelvin. Recall that 0°C + 273.15 = 273.15K" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": {}, + "outputs": [], + "source": [ + "# Your code here:\n", + "\n", + "lambda_kelvin = lambda x: x + 273.15 # La funcion lambda se encargara de transformar la temperatura" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally, convert the list of temperatures below from Celsius to Kelvin." + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[285.15, 296.15, 311.15, 218.14999999999998, 297.15]\n" + ] + } + ], + "source": [ + "temps = [12, 23, 38, -55, 24]\n", + "\n", + "# Your code here:\n", + "temps_kelvin = []\n", + "temps_kelvin = [lambda_kelvin(i) for i in temps] # Le pasamos a lambda cada uno de los valores de temps y lo transforma a kelvin\n", + "print(temps_kelvin)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### In this part, we will define a function that returns a lambda expression\n", + "\n", + "In the cell below, write a lambda expression that takes two numbers and returns 1 if one is divisible by the other and zero otherwise. Call the lambda expression `mod`." + ] + }, + { + "cell_type": "code", + "execution_count": 108, + "metadata": {}, + "outputs": [], + "source": [ + "# Your code here:\n", + "mod = lambda x, y: 1 if x % y == 0 else 0" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Now create a function that returns mod. The function only takes one argument - the first number in the `mod` lambda function. \n", + "\n", + "Note: the lambda function above took two arguments, the lambda function in the return statement only takes one argument but also uses the argument passed to the function." + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": {}, + "outputs": [], + "source": [ + "def divisor(b):\n", + " \"\"\"\n", + " input: a number\n", + " output: a function that returns 1 if the number is divisible by another number (to be passed later) and zero otherwise\n", + " \"\"\"\n", + " \n", + " # Your code here:\n", + " return lambda x: mod(x, b) # Definimos en el return otra funcion lambda en donde llamamos a la funcion lambda mod" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally, pass the number 5 to `divisor`. Now the function will check whether a number is divisble by 5. Assign this function to `divisible5`" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [], + "source": [ + "# Your code here:\n", + "divisible5 = divisor(5) # Definimos que b es 5 y creamos una especie de subfuncion llamada divisible5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Test your function with the following test cases:" + ] + }, + { + "cell_type": "code", + "execution_count": 111, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 111, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "divisible5(10) # Llamamos nuestra subfuncion y le pasamos el valor que queremos saber si es divisible entre 5\n", + " # Este valor lo toma la funcion lambda dentro del return y lo envia a nuestra funcion mod (es x)" + ] + }, + { + "cell_type": "code", + "execution_count": 112, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 112, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "divisible5(8)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 2 - Using Lambda Expressions in List Comprehensions\n", + "\n", + "In the following challenge, we will combine two lists using a lambda expression in a list comprehension. \n", + "\n", + "To do this, we will need to introduce the `zip` function. The `zip` function returns an iterator of tuples.\n", + "\n", + "The way zip function works with list has been shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": 113, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[('Green', 'eggs'),\n", + " ('cheese', 'cheese'),\n", + " ('English', 'cucumber'),\n", + " ('tomato', 'tomato')]" + ] + }, + "execution_count": 113, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list1 = ['Green', 'cheese', 'English', 'tomato']\n", + "list2 = ['eggs', 'cheese', 'cucumber', 'tomato']\n", + "zipped = zip(list1,list2)\n", + "list(zipped)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this exercise we will try to compare the elements on the same index in the two lists. \n", + "We want to zip the two lists and then use a lambda expression to compare if:\n", + "list1 element > list2 element " + ] + }, + { + "cell_type": "code", + "execution_count": 114, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[(1, 2), (2, 3), (3, 4), (4, 5)]\n" + ] + } + ], + "source": [ + "list1 = [1,2,3,4]\n", + "list2 = [2,3,4,5]\n", + "## Zip the lists together\n", + "zip_list = zip(list1, list2)\n", + "## Print the zipped list \n", + "print(list(zip_list))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Complete the parts of the code marked as \"###\"" + ] + }, + { + "cell_type": "code", + "execution_count": 115, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "False\n", + "False\n", + "False\n" + ] + } + ], + "source": [ + "'''\n", + "\n", + "compare = lambda ###: print(\"True\") if ### else print(\"False\")\n", + "for ### in zip(list1,list2):\n", + " compare(###)\n", + " \n", + "''' \n", + "\n", + "compare = lambda x, y: print('True') if x > y else print('False')\n", + "for x, y in zip(list1, list2):\n", + " compare(x, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 3 - Using Lambda Expressions as Arguments\n", + "\n", + "#### In this challenge, we will zip together two lists and sort by the resulting tuple.\n", + "\n", + "In the cell below, take the two lists provided, zip them together and sort by the first letter of the second element of each tuple. Do this using a lambda function." + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[('Political Science', 'Essay'),\n", + " ('Computer Science', 'Homework'),\n", + " ('Engineering', 'Lab'),\n", + " ('Mathematics', 'Module')]" + ] + }, + "execution_count": 124, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list1 = ['Engineering', 'Computer Science', 'Political Science', 'Mathematics']\n", + "list2 = ['Lab', 'Homework', 'Essay', 'Module']\n", + "\n", + "# Your code here:\n", + "zip_list = zip(list1, list2)\n", + "sorted(zip_list, key = lambda x: x[1]) # Le pedimos que la key con la que va a hacer el sorting va a ser el segundo elemento\n", + " # de cada uno de las tuplas presente en las listas" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Bonus Challenge - Sort a Dictionary by Values\n", + "\n", + "Given the dictionary below, sort it by values rather than by keys. Use a lambda function to specify the values as a sorting key." + ] + }, + { + "cell_type": "code", + "execution_count": 125, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[('Toyota', 1995), ('Honda', 1997), ('Audi', 2001), ('BMW', 2005)]" + ] + }, + "execution_count": 125, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d = {'Honda': 1997, 'Toyota': 1995, 'Audi': 2001, 'BMW': 2005}\n", + "\n", + "# Your code here:\n", + "sorted(d.items(), key = lambda x: x[1]) # Hacemos lo mismo que en el caso anterior ya que .items nos devuelve una lista\n", + " # con tuplas\n", + " \n", + "# Con la funcion sorted y usando una lambda podemos hacer un sort de una columna especifica en una tabla de datos" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "#d.items()\n", + "#sorted(d.items(), key = operator.itemgetter(1))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/your-code/Learning.ipynb b/your-code/Learning.ipynb index 93dd25f..ecb174e 100755 --- a/your-code/Learning.ipynb +++ b/your-code/Learning.ipynb @@ -283,7 +283,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.2" + "version": "3.8.8" } }, "nbformat": 4, diff --git a/your-code/main.ipynb b/your-code/main.ipynb index 66a9984..d35df0a 100755 --- a/your-code/main.ipynb +++ b/your-code/main.ipynb @@ -34,18 +34,28 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 105, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n" + ] + } + ], "source": [ - "l = [######]\n", - "f = lambda x: #define the lambda expression\n", + "l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", + "f = lambda x: x + 5\n", "b = []\n", + "\n", "def modify_list(lst, fudduLambda):\n", - " for x in ####:\n", - " b.append(#####(x))\n", - "#Call modify_list(##,##)\n", - "#print b" + " for x in lst:\n", + " b.append(fudduLambda(x))\n", + " \n", + "modify_list(l, f)\n", + "print(b)" ] }, { @@ -59,12 +69,13 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 106, "metadata": {}, "outputs": [], "source": [ "# Your code here:\n", - "\n" + "\n", + "lambda_kelvin = lambda x: x + 273.15 # La funcion lambda se encargara de transformar la temperatura" ] }, { @@ -76,13 +87,24 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 107, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[285.15, 296.15, 311.15, 218.14999999999998, 297.15]\n" + ] + } + ], "source": [ "temps = [12, 23, 38, -55, 24]\n", "\n", - "# Your code here:" + "# Your code here:\n", + "temps_kelvin = []\n", + "temps_kelvin = [lambda_kelvin(i) for i in temps] # Le pasamos a lambda cada uno de los valores de temps y lo transforma a kelvin\n", + "print(temps_kelvin)" ] }, { @@ -96,11 +118,12 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 108, "metadata": {}, "outputs": [], "source": [ - "# Your code here:\n" + "# Your code here:\n", + "mod = lambda x, y: 1 if x % y == 0 else 0" ] }, { @@ -114,7 +137,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 109, "metadata": {}, "outputs": [], "source": [ @@ -124,7 +147,8 @@ " output: a function that returns 1 if the number is divisible by another number (to be passed later) and zero otherwise\n", " \"\"\"\n", " \n", - " # Your code here:" + " # Your code here:\n", + " return lambda x: mod(x, b) # Definimos en el return otra funcion lambda en donde llamamos a la funcion lambda mod" ] }, { @@ -136,11 +160,12 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 110, "metadata": {}, "outputs": [], "source": [ - "# Your code here:\n" + "# Your code here:\n", + "divisible5 = divisor(5) # Definimos que b es 5 y creamos una especie de subfuncion llamada divisible5" ] }, { @@ -152,18 +177,41 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 111, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 111, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "divisible5(10)" + "divisible5(10) # Llamamos nuestra subfuncion y le pasamos el valor que queremos saber si es divisible entre 5\n", + " # Este valor lo toma la funcion lambda dentro del return y lo envia a nuestra funcion mod (es x)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 112, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 112, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "divisible5(8)" ] @@ -183,7 +231,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 113, "metadata": {}, "outputs": [ { @@ -195,7 +243,7 @@ " ('tomato', 'tomato')]" ] }, - "execution_count": 1, + "execution_count": 113, "metadata": {}, "output_type": "execute_result" } @@ -218,14 +266,24 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 114, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[(1, 2), (2, 3), (3, 4), (4, 5)]\n" + ] + } + ], "source": [ "list1 = [1,2,3,4]\n", "list2 = [2,3,4,5]\n", - "## Zip the lists together \n", - "## Print the zipped list " + "## Zip the lists together\n", + "zip_list = zip(list1, list2)\n", + "## Print the zipped list \n", + "print(list(zip_list))" ] }, { @@ -237,18 +295,18 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 115, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "'\\n\\ncompare = lambda ###: print(\"True\") if ### else print(\"False\")\\nfor ### in zip(list1,list2):\\n compare(###)\\n \\n'" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "False\n", + "False\n", + "False\n" + ] } ], "source": [ @@ -258,7 +316,11 @@ "for ### in zip(list1,list2):\n", " compare(###)\n", " \n", - "''' " + "''' \n", + "\n", + "compare = lambda x, y: print('True') if x > y else print('False')\n", + "for x, y in zip(list1, list2):\n", + " compare(x, y)" ] }, { @@ -274,14 +336,31 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 124, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[('Political Science', 'Essay'),\n", + " ('Computer Science', 'Homework'),\n", + " ('Engineering', 'Lab'),\n", + " ('Mathematics', 'Module')]" + ] + }, + "execution_count": 124, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "list1 = ['Engineering', 'Computer Science', 'Political Science', 'Mathematics']\n", "list2 = ['Lab', 'Homework', 'Essay', 'Module']\n", "\n", - "# Your code here:\n" + "# Your code here:\n", + "zip_list = zip(list1, list2)\n", + "sorted(zip_list, key = lambda x: x[1]) # Le pedimos que la key con la que va a hacer el sorting va a ser el segundo elemento\n", + " # de cada uno de las tuplas presente en las listas" ] }, { @@ -295,13 +374,38 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 125, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[('Toyota', 1995), ('Honda', 1997), ('Audi', 2001), ('BMW', 2005)]" + ] + }, + "execution_count": 125, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "d = {'Honda': 1997, 'Toyota': 1995, 'Audi': 2001, 'BMW': 2005}\n", "\n", - "# Your code here:" + "# Your code here:\n", + "sorted(d.items(), key = lambda x: x[1]) # Hacemos lo mismo que en el caso anterior ya que .items nos devuelve una lista\n", + " # con tuplas\n", + " \n", + "# Con la funcion sorted y usando una lambda podemos hacer un sort de una columna especifica en una tabla de datos" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "#d.items()\n", + "#sorted(d.items(), key = operator.itemgetter(1))" ] }, { @@ -328,7 +432,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.3" + "version": "3.8.8" } }, "nbformat": 4,