{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python \n", "\n", "## [Functional Programming](https://docs.python.org/3/howto/functional.html) with Python:\n", "\n", "+ #### _lambda_ functions \n", "+ #### _zip_ \n", "+ #### _map_ \n", "+ #### _filter_ \n", "+ #### _reduce_ " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import time" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## lambda Functions\n", "\n", "When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way. If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all, as in these examples:\n", "\n", " stripped_lines = [line.strip() for line in lines]\n", " existing_files = filter(os.path.exists, file_list)\n", "\n", "If the function you need doesn’t exist, you need to write it. \n", "One way to write small functions is to use the _lambda_ expression. lambda takes a number of parameters and an expression combining these parameters, and creates an anonymous function that returns the value of the expression:\n", "\n", "The pattern is: \n", "\n", " lambda < variables > : operation(< variables >)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Examples" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def adder(x, y):\n", " return x + y" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "78.6 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n" ] } ], "source": [ "%%timeit\n", "\n", "adder(3,4)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "adder_lambda = lambda x, y: x+y" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "82.7 ns ± 0.878 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n" ] } ], "source": [ "%%timeit\n", "\n", "adder_lambda(3,4)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "general_adder = lambda *x : sum(x)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "general_adder(2,3,4,5)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "square = lambda x: x**2" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "square(2)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def print_assign(name, value):\n", " return name + '=' + str(value)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "print_assign = lambda name, value: name + '=' + str(value)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'year=2020'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print_assign('year',2020)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "even = lambda x:True if x%2==0 else False" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "print(even(17))\n", "print(even(16))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Dictionary of functions" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "power = {'square': lambda x:x**2, \n", " 'cube': lambda x:x**3,\n", " 'fourth': lambda x:x**4\n", " }" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'square': (x)>,\n", " 'cube': (x)>,\n", " 'fourth': (x)>}" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "power" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "function" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(power[\"cube\"])" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "729\n", "9\n", "2401\n" ] } ], "source": [ "print(power['cube'](9))\n", "\n", "print(power['square'](3))\n", "\n", "print(power['fourth'](7))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ at 0x7f46dc625560>, at 0x7f46dc6258c0>]\n" ] }, { "data": { "text/plain": [ "[1, 4, 9, 0, 1, 2]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "funcs = [lambda x:x**2, lambda x:x-1]\n", "print(funcs)\n", "[func(x) for func in funcs for x in [1,2,3]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functional Tools: _zip_, _filter_, _map_ , _reduce_ " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## [_zip_](https://medium.com/techtofreedom/7-levels-of-using-the-zip-function-in-python-a4bd22ee8bcd)\n", "\n", "+ #### _zip_ function returns a _zip_ object (which is an iterator) that will aggregate elements from two or more iterables. \n", "+ #### You can use the resulting iterator to solve common tasks, like creating dictionaries. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "sq1 = [1,2,3,4,5,6,7,8]\n", "sq2 = ['a','b','c','d','e','f']\n", "z = zip(sq1,sq2)\n", "print(z)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 'a')" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(z)\n", "#z.__next__()" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 'a')\n", "(2, 'b')\n", "(3, 'c')\n", "(4, 'd')\n", "(5, 'e')\n", "(6, 'f')\n" ] } ], "source": [ "z = zip(sq1,sq2)\n", "for t in z:\n", " print(t)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z = zip(sq1,sq2)\n", "list(z)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Leticia': 8, 'Ana': 9, 'Raquel': 10}" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "names = ['Leticia', 'Ana', 'Raquel']\n", "grades = [8,9,10]\n", "dic_grades = dict(zip(names,grades))\n", "dic_grades" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Zip trims to the length of the smaller sequence" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Diogo': 0, 'Rafael': 1, 'Gustavo': 2, 'Deborah': 3}\n" ] } ], "source": [ "students = ['Diogo','Rafael','Gustavo','Deborah', 'Extra Student']\n", "grades = [0,1,2,3]\n", "new_dict_grades = dict(zip(students,grades))\n", "print(new_dict_grades)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]\n", "[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]\n" ] } ], "source": [ "list1 = list(range(11))\n", "list2 = list(range(1,30,2))\n", "list3 = list(range(1,100,5))\n", "print(list1)\n", "print(list2)\n", "print(list3)" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(0, 1, 1), (1, 3, 6), (2, 5, 11), (3, 7, 16), (4, 9, 21), (5, 11, 26), (6, 13, 31), (7, 15, 36), (8, 17, 41), (9, 19, 46), (10, 21, 51)]\n" ] } ], "source": [ "zipped = list(zip(list1, list2, list3))\n", "print(zipped)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### For unequal length sequences we can use zip_logest from itertools" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from itertools import zip_longest\n", "\n", "id = [1, 2]\n", "leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 'Elon Mask'), (2, 'Tim Cook'), (None, 'Bill Gates'), (None, 'Yang Zhou')]\n" ] } ], "source": [ "long_record = zip_longest(id, leaders)\n", "print(list(long_record))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 'Elon Mask'), (2, 'Tim Cook'), ('Top', 'Bill Gates'), ('Top', 'Yang Zhou')]\n" ] } ], "source": [ "long_record_2 = zip_longest(id, leaders, fillvalue='Top')\n", "print(list(long_record_2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### How to reverse a zip command?" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "((1, 2), (3, 4), (4, 5))" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1 = ((1,2),(3,4),(4,5))\n", "print(t1)\n", "print(*t1)" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(0, 1, 1) (1, 3, 6) (2, 5, 11) (3, 7, 16) (4, 9, 21) (5, 11, 26) (6, 13, 31) (7, 15, 36) (8, 17, 41) (9, 19, 46) (10, 21, 51)\n" ] } ], "source": [ "print(*zipped)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10),\n", " (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21),\n", " (1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51)]" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "unzipped = (zip(*zipped))\n", "list(unzipped)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using Zip with comprehensions" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6}" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sq1 = [1,2,3,4,5,6,7,8]\n", "sq2 = ['a','b','c','d','e','f']\n", "d3 = {x.upper():y for y,x in zip(sq1,sq2)}\n", "d3" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'b', 'c', 'd', 'e', 'f']\n", "[1, 2, 3, 4, 5, 6]\n" ] }, { "data": { "text/plain": [ "{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 = [x.lower() for x in d3.keys()]\n", "s2 = [x for x in d3.values()]\n", "print(s1)\n", "print(s2)\n", "d4 = {k:v for k,v in zip(s1,s2)}\n", "d4" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 'a', 'w'), (2, 'b', 'e'), (3, 'c', 'r'), (4, 'd', 'y')]\n" ] } ], "source": [ "sq1 = [1,2,3,4,5,6,7,8]\n", "sq2 = ['a','b','c','d','e','f']\n", "sq3 = ['w','e','r','y']\n", "z4 = zip(sq1,sq2,sq3)\n", "print(list(z4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using zip tp transpose a matrix" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1, 1], [2, 2], [3, 3]]\n" ] } ], "source": [ "matrix = [[1, 2, 3], [1, 2, 3]]\n", "matrix_T = [list(i) for i in zip(*matrix)]\n", "print(matrix_T)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _map_\n", "\n", "+ #### _map_ function returns a map object (which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) \n", "+ #### Maps are similar to [list comprehensions](https://stackoverflow.com/questions/1247486/list-comprehension-vs-map) but they create generators instead of lists" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "def my_function(x):\n", " return x**10" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1048576\n", "10000000000\n" ] } ], "source": [ "print(my_function(4))\n", "print(my_function(10))" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "seq6 = [3,7,9,1,5,7]" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[59049, 282475249, 3486784401, 1, 9765625, 282475249]\n", "\n", "CPU times: user 512 µs, sys: 0 ns, total: 512 µs\n", "Wall time: 270 µs\n" ] } ], "source": [ "%%time\n", "\n", "results = map(my_function, seq6)\n", "\n", "print(list(results))\n", "print(type(results))" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[59049, 282475249, 3486784401, 1, 9765625, 282475249]\n", "\n", "CPU times: user 372 µs, sys: 0 ns, total: 372 µs\n", "Wall time: 216 µs\n" ] } ], "source": [ "%%time\n", "\n", "results = [my_function(x) for x in seq6]\n", "\n", "print(results)\n", "print(type(results))" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[59049, 282475249, 3486784401, 1, 9765625, 282475249]\n", "\n", "CPU times: user 633 µs, sys: 0 ns, total: 633 µs\n", "Wall time: 402 µs\n" ] } ], "source": [ "%%time\n", "\n", "results = map(lambda x:x**10, seq6)\n", "\n", "print(list(results))\n", "print(type(results))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _reduce_\n", "\n", "+ #### The reduce() function in Python takes in a function and a list as argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of functools module." ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "from functools import reduce" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3628800" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "seq9 = [1,2,3,4,5,6,7,8,9,10]\n", "multiply = reduce(lambda x,y:x*y, seq9)\n", "multiply" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'ABCDEFg'" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "seq10 = ['a','b','c','d','e','f','g']\n", "concatenate = reduce(lambda x,y:x.upper()+y, seq10)\n", "concatenate" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "list1 = list(range(11))\n", "list2 = list(range(1,30,2))\n", "list3 = list(range(1,100,5))" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "385" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soma = reduce(lambda x,y:x+y**2,list1)\n", "soma" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4495" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soma2 = reduce(lambda x,y:x+y**2,list2)\n", "soma2" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "63670" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soma3 = reduce(lambda x,y:x+y**2,list3)\n", "soma3" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.3164075131513564, 0.884567334784409, 0.9142504575092464, 0.6994761960912965, 0.0590453936212596, 0.45013360545153347, 0.5937569416081616, 0.3455401815537914, 0.5898892899783473, 0.8749676480882057]\n" ] } ], "source": [ "import random\n", "seq = [random.random() for x in range(10)]\n", "print(seq)" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.9142504575092464" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(seq)" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.9142504575092464" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "compara = lambda x,y: x if x>=y else y\n", "reduce(compara,seq)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _filter_\n", "\n", "+ #### The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. This function must return a boolean value. " ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [], "source": [ "my_string = 'aAbRmmmTTTBfgHHrTEB'" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'b', 'm', 'm', 'm', 'f', 'g', 'r']\n", "\n" ] } ], "source": [ "resp = filter(lambda x:x.islower(), my_string)\n", "print(list(resp))\n", "print(type(resp))" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A', 'R', 'T', 'T', 'T', 'B', 'H', 'H', 'T', 'E', 'B']\n", "\n" ] } ], "source": [ "resp = filter(lambda x: not x.islower(), my_string)\n", "print(list(resp))\n", "print(type(resp))" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A', 'R', 'T', 'T', 'T', 'B', 'H', 'H', 'T', 'E', 'B']\n", "\n" ] } ], "source": [ "resp = filter(lambda x:x.isupper(), my_string)\n", "print(list(resp))\n", "print(type(resp))" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.4933665026342463,\n", " 0.5452572345679209,\n", " 0.9457092223731333,\n", " 0.9322593404797879,\n", " 0.9999951742442206]" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list1 = [random.random() for x in range(10)]\n", "bigger_than_dot4 = filter(lambda x:x>0.4,list1)\n", "list(bigger_than_dot4)" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['In',\n", " 'the',\n", " 'beginning',\n", " 'God',\n", " 'created',\n", " 'the',\n", " 'heaven',\n", " 'and',\n", " 'the',\n", " 'earth.']" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simplified_genesis = '''\n", "In the beginning God created the heaven and the earth. \n", "And the earth was without form, and void; and darkness \n", "was upon the face of the deep. And the Spirit of God \n", "moved upon the face of the waters. And God said, \n", "Let there be light: and there was light.'''\n", "\n", "simplified_genesis.split()[0:10]" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [], "source": [ "istitle = lambda x : x.istitle() " ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['In', 'God', 'And', 'And', 'Spirit', 'God', 'And', 'God', 'Let']\n", "['In', 'God', 'And', 'And', 'Spirit', 'God', 'And', 'God', 'Let']\n", "['In', 'God', 'And', 'And', 'Spirit', 'God', 'And', 'God', 'Let']\n" ] } ], "source": [ "print(list(filter(istitle, simplified_genesis.split())))\n", "print(list(filter(lambda x: x.istitle(), simplified_genesis.split())))\n", "print(list(filter(str.istitle, simplified_genesis.split())))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Implementing the builtin generators as ordinary functions:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _zip_:" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [], "source": [ "def my_zip(*sequences):\n", " smaller = min([len(sequence) for sequence in sequences])\n", " for i in range(smaller):\n", " yield(tuple([sequence[i] for sequence in sequences]))" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "zipped = my_zip([1,2,3,5],[5,6,7],[3,2,5])\n", "print(type(zipped))" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 5, 3), (2, 6, 2), (3, 7, 5)]\n" ] } ], "source": [ "print(list(zipped))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _map_:" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [], "source": [ "## option 1 - create a generator\n", "\n", "def my_map(func, sequence):\n", " for element in (sequence):\n", " yield(func(element))" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [], "source": [ "## option 2 - return a generator\n", "\n", "def my_map(func, sequence):\n", " mapped = (func(item) for item in sequence)\n", " return mapped" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [], "source": [ "mapped = my_map(lambda x:x**2, [1,2,3,4,5])" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 143, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(mapped)" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16, 25]\n" ] } ], "source": [ "print(list(mapped))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _filter_:" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [], "source": [ "## option 1 - create a generator\n", "\n", "def my_filter(func_bool, sequence):\n", " filtered = (item for item in sequence if func_bool(item))\n", " for element in filtered:\n", " yield(element)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## option 2 - return a generator\n", "\n", "def my_filter(func_bool, sequence):\n", " filtered = (item for item in sequence if func_bool(item))\n", " return filtered" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [], "source": [ "filtered = my_filter(lambda x:x%2==0, [1,2,3,4,5,6])" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 139, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(filtered)" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6]\n" ] } ], "source": [ "print(list(filtered))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _range_:" ] }, { "cell_type": "code", "execution_count": 172, "metadata": {}, "outputs": [], "source": [ "def my_range(*args):\n", " start = 0\n", " step = 1\n", " \n", " if len(args) == 1:\n", " end = args[0]\n", " elif len(args) == 2:\n", " start = args[0]\n", " end = args[1]\n", " elif len(args) == 3:\n", " start = args[0]\n", " end = args[1]\n", " step = args[2]\n", " else:\n", " print('Too few or too many arguments')\n", " return\n", " \n", " while start < end:\n", " yield start\n", " start += step" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "print(list(my_range(10)))" ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6, 8]\n" ] } ], "source": [ "print(list(my_range(2,10,2)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## _reduce_:" ] }, { "cell_type": "code", "execution_count": 187, "metadata": {}, "outputs": [], "source": [ "def my_reduce(function, sequence):\n", " result = sequence[0]\n", " for i in range(len(sequence)-1):\n", " result = function(result,sequence[i+1])\n", " return result" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "28" ] }, "execution_count": 188, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_reduce(lambda x,y:x+y, [1,2,3,4,5,6,7])" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10" } }, "nbformat": 4, "nbformat_minor": 4 }