{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{' ', ',', 'B', 'S', 'a', 'c', 'e', 'i', 'l', 'm', 'o', 'p', 's', 't', 'u'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = set(\"Beam me up Scottie, please\")\n", "s" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# many set operations are provided\n", "# we will not go into details" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Next we move on to functions and maps\n", "# Let's define the square function\n", "def sq(x):\n", " return x**2" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 4, 9, 16]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# We now apply the function\n", "squares = []\n", "for i in range(5):\n", " squares.append(sq(i))\n", "squares" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n" ] } ], "source": [ "# We can do the above task in a different way using maps\n", "# We can use maps to apply a function to a list of items\n", "sqs = map(sq, range(10))\n", "print(list(sqs))" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 5, 7, 6, 5, 5]\n" ] } ], "source": [ "names = ['Ana', 'Amira', 'Barbara', 'Camila', 'Diego', 'Zorro']\n", "print(list(map(len,names)))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 3, 5, 13, 21, 55]\n" ] } ], "source": [ "# Now for filtering\n", "fib = [0,1,1,2,3,5,8,13,21,34,55]\n", "# filter out all even numbers\n", "odd = list(filter(lambda x: x % 2, fib))\n", "print(odd)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 8, 34]\n" ] } ], "source": [ "print(list(filter(lambda x: x % 2 - 1, fib)))" ] }, { "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }