{"id":5666,"date":"2022-06-01T19:09:32","date_gmt":"2022-06-01T19:09:32","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/01\/python-for-machine-learning-7-day-mini-course\/"},"modified":"2022-06-01T19:09:32","modified_gmt":"2022-06-01T19:09:32","slug":"python-for-machine-learning-7-day-mini-course","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/01\/python-for-machine-learning-7-day-mini-course\/","title":{"rendered":"Python for Machine Learning (7-day mini-course)"},"content":{"rendered":"<p>Author: Adrian Tam<\/p>\n<div>\n<h4 style=\"text-align: center;\">Python for Machine Learning Crash Course.<br \/>\nLearn core Python in 7 days.<\/h4>\n<p>Python is an amazing programming language. Not only it is widely used in machine learning projects, you can also find its presence in system tools, web projects, and many others. Having good Python skills can make you work more efficiently because it is famous for its simplicity. You can try out your idea faster. You can also present your idea in a concise code in Python.<\/p>\n<p>As a practitioner, you are not required to know how the language is built, but you should know that the language can help you in various tasks. You can see how concise a Python code can be, and how much the functions from its libraries can do.<\/p>\n<p>In this crash course, you will discover some common Python techniques, from doing the exercises in seven days.<\/p>\n<p>This is a big and important post. You might want to bookmark it.<\/p>\n<p>Let\u2019s get started.<\/p>\n<div id=\"attachment_11271\" style=\"width: 809px\" class=\"wp-caption aligncenter\">\n<img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-11271\" class=\"size-full wp-image-11271\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2022\/06\/david-clode-vec5yfUvCGs-unsplash-scaled.jpg\" alt=\"Python for Machine Learning (7-Day Mini-Course)\" width=\"799\" height=\"554\"><\/p>\n<p id=\"caption-attachment-11271\" class=\"wp-caption-text\">Python for Machine Learning (7-Day Mini-Course)<br \/>Photo by <a href=\"https:\/\/unsplash.com\/photos\/vec5yfUvCGs\">David Clode<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2>Who Is This Crash-Course For?<\/h2>\n<p>Before you get started, let\u2019s make sure you are in the right place.<\/p>\n<p>This course is for developers who may know some programming. Maybe you know another language, or you may be able to write a few lines of code in Python to do something simple.<\/p>\n<p>The lessons in this course do assume a few things about you, such as:<\/p>\n<ul>\n<li>You know your way around basic Python.<\/li>\n<li>You understand the basic programming concepts, such as variables, arrays, loops, and functions.<\/li>\n<li>You can work with Python in command line or inside an IDE.<\/li>\n<\/ul>\n<p>You do NOT need to be:<\/p>\n<ul>\n<li>A star programmer<\/li>\n<li>A Python expert<\/li>\n<\/ul>\n<p>This crash course can help you transform from a novice programmer to an expert who can code comfortably in Python.<\/p>\n<p>This crash course assumes you have a working Python 3.7 environment installed. If you need help with your environment, you can follow the step-by-step tutorial here:<\/p>\n<ul>\n<li><a href=\"https:\/\/machinelearningmastery.com\/setup-python-environment-machine-learning-deep-learning-anaconda\/\">How to Set Up Your Python Environment for Machine Learning With Anaconda<\/a><\/li>\n<\/ul>\n<h2>Crash-Course Overview<\/h2>\n<p>This crash course is broken down into seven lessons.<\/p>\n<p>You could complete one lesson per day (recommended) or complete all of the lessons in one day (hardcore). It really depends on the time you have available and your level of enthusiasm.<\/p>\n<p>Below is a list of the seven lessons that will get you started and productive with Python:<\/p>\n<ul>\n<li>\n<strong>Lesson 01<\/strong>: Manipulating lists<\/li>\n<li>\n<strong>Lesson 02<\/strong>: Dictionaries<\/li>\n<li>\n<strong>Lesson 03<\/strong>: Tuples<\/li>\n<li>\n<strong>Lesson 04<\/strong>: Strings<\/li>\n<li>\n<strong>Lesson 05<\/strong>: List comprehension<\/li>\n<li>\n<strong>Lesson 06<\/strong>: Enumerate and zip<\/li>\n<li>\n<strong>Lesson 07<\/strong>: Map, filter, and reduce<\/li>\n<\/ul>\n<p>Each lesson could take you between 5 and up to 30 minutes. Take your time and complete the lessons at your own pace. Ask questions, and even post results in the comments online.<\/p>\n<p>The lessons might expect you to go off and find out how to do things. This guide will give you hints, but part of the point of each lesson is to force you to learn where to go to look for help with and about the algorithms and the best-of-breed tools in Python.<\/p>\n<p><strong>Post your results in the comments<\/strong>; I\u2019ll cheer you on!<\/p>\n<p>Hang in there; don\u2019t give up.<\/p>\n<h2>Lesson 01: Manipulating lists<\/h2>\n<p>In this lesson, you will discover a basic data structures in Python, the list.<\/p>\n<p>In other programming languages, there are arrays. The counterpart in Python is <strong>list<\/strong>. A Python list does not limit the number of elements it stores. You can always append elements into it, and it will automatically expand its size. Python list also does not require its elements to be in the same type. You can mix and match different elements into a list.<\/p>\n<p>In the following, we create a list of some integers, and then append a string into it:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [1, 2, 3]\r\nx.append(\"that's all\")<\/pre>\n<p>Python lists are zero-indexed. Namely, to get the first element in the above list, we do:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">print(x[0])<\/pre>\n<p>This will print <code>1<\/code> to the screen.<\/p>\n<p>Python lists allow negative indices to mean counting elements from the back. So the way to print the last element from the above list is:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">print(x[-1])<\/pre>\n<p>Python also has a handy syntax to find a slice of a list. To print the last two elements, we do:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">print(x[-2:])<\/pre>\n<p>Usually, the slice syntax is <code>start:end<\/code> where the end is not included in the result. If omitted, the default will be the first element as the start and the one beyond the end of the entire list as the end. We can also use the slice syntax to make a <code><\/code>step.\u201d For example, this is how we can extract even and odd numbers:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\nodd = x[::2]\r\neven = x[1::2]\r\nprint(odd)\r\nprint(even)<\/pre>\n<\/p>\n<h3>Your Task<\/h3>\n<p>In the above example of getting odd numbers from a list of 1 to 10, you can make a step size of <code>-2<\/code> to ask the list go backward. How can you use the slicing syntax to print <code>[9,7,5,3,1]<\/code>? How about <code>[7,5,3]<\/code>?<\/p>\n<p>Post your answer in the comments below. I would love to see what you come up with.<\/p>\n<p>In the next lesson, you will discover the Python dictionary.<\/p>\n<h2>Lesson 02: Dictionaries<\/h2>\n<p>In this lesson, you will learn Python\u2019s way of storing a mapping.<\/p>\n<p>Similar to Perl, an associative array is also a native data structure in Python. It is called a dictionary or dict. Python uses square brackets <code>[]<\/code> for list and uses curly brackets <code>{}<\/code> for dict. A Python dict is for key-value mapping, but the key must be <strong>hashable<\/strong>, such as a number or a string. Hence we can do the following:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">price = {\r\n    \"apple\": 1.5,\r\n    \"orange\": 1.25,\r\n    \"banana\": 0.5\r\n}\r\nprint(\"apple costs $\", price[\"apple\"])<\/pre>\n<p>Adding a key-value mapping to a dict is similar to indexing a list:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">price[\"lemon\"] = 0.6\r\nprint(\"lemon costs $\", price[\"lemon\"])<\/pre>\n<p>We can check if a key is in a dict using the codetext{in} operator, for example:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">if \"strawberry\" in price:\r\n    # if price is not found, assume $1\r\n    print(\"strawberry costs $1\")\r\nelse:\r\n    print(\"strawberry costs $\", price[\"strawberry\"])<\/pre>\n<p>But in Python dict, we can use the codetext{get()} function to give us a default value if the key is not found:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">print(\"strawberry costs $\", price.get(\"strawberry\", 1))<\/pre>\n<p>But indeed, you are not required to provide a default to codetext{get()}. If you omitted it, it will return codetext{None}. For example:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">print(\"strawberry costs $\", price.get(\"strawberry\"))<\/pre>\n<p>It will produce<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">strawberry costs $ None<\/pre>\n<p>Since the Python dict is a key-value mapping, we can extract only the keys or only the values, using:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">fruits = list(price.keys())\r\nnumbers = list(price.values())\r\nprint(fruits)\r\nprint(numbers)<\/pre>\n<p>We used <code>list()<\/code> to convert the keys or values to a list for better printing.<br \/>\n%<br \/>\nThe other way to manipulate a list is with the <code>items()<\/code> function. Its result would be key-value pairs:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">pairs = list(price.items())\r\nprint(pairs)<\/pre>\n<p>This prints:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">[('apple', 1.5), ('orange', 1.25), ('banana', 0.5), ('lemon', 0.6)]<\/pre>\n<p>Since they are pairs in a list, we can use list manipulation syntax to combine items from two dicts and produce a combined dict. The following is an example:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">price1 = {\r\n    \"apple\": 1.5,\r\n    \"orange\": 1.25,\r\n    \"strawberry\": 1.0\r\n}\r\nprice2 = {\r\n    \"banana\": 0.5\r\n}\r\npairs1 = list(price1.items())\r\npairs2 = list(price2.items())\r\nprice = dict(pairs1 + pairs2)\r\nprint(price)<\/pre>\n<p>This will print:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">{'apple': 1.5, 'orange': 1.25, 'strawberry': 1.0, 'banana': 0.5}<\/pre>\n<\/p>\n<h3>Your Task<\/h3>\n<p>Depending on your version of Python, the last example above can have a simplified syntax:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">price = price1 | price2\r\nprice = {**price1, **price2}<\/pre>\n<p>Check in your installation if you can reproduce the same result as the last example.<\/p>\n<p>In the next lesson, you will discover the tuple as a read-only list.<\/p>\n<h2>Lesson 03: Tuples<\/h2>\n<p>In this lesson, you will learn the tuple as a read-only data structure.<\/p>\n<p>Python has a list that behaves like an array of mixed data. A Python tuple is very much like a list, but it cannot be modified after it is created. It is <strong>immutable<\/strong>. Creating a tuple is just like creating a list, except using parentheses, <code>()<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = (1, 2, 3)<\/pre>\n<p>You can refer to the first element as <code>x[0]<\/code> just like the case of a list. But you cannot assign a new value to <code>x[0]<\/code> because a tuple is immutable. If you try to do it, Python will throw a TypeError with the reason that the tuple does not support the item assignment.<\/p>\n<p>A tuple is handy to represent multiple return values of a function. For example, the following function produces a value\u2019s multiple powers as a tuple:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">def powers(n):\r\n    return n, n**2, n**3\r\nx = powers(2)\r\nprint(x)<\/pre>\n<p>This will print:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">(2, 4, 8)<\/pre>\n<p>which is a tuple. But we usually use the unpacking syntax:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">itself, squared, cubed = powers(2)<\/pre>\n<p>In fact, this is a powerful syntax in Python in which we can assign multiple variables in one line. For example,<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">count, elements = 0, []<\/pre>\n<p>This will assign variable <code>count<\/code> to integer <code>0<\/code> and variable <code>elements<\/code> to an empty list. Because of the unpacking syntax, this is the <strong>Pythonic<\/strong> way of swapping the value of two variables:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">a, b = b, a<\/pre>\n<\/p>\n<h3>Your Task<\/h3>\n<p>Consider a list of tuples:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [(\"alpha\", 0.5), (\"gamma\", 0.1), (\"beta\", 1.1), (\"alpha\", -3)]<\/pre>\n<p>You can sort this list using <code>sorted(x)<\/code>. What is the result? From the result of comparing tuples, how does Python understand which tuple is less than or greater than another? Which is greater, the tuple <code>(\"alpha\", 0.5)<\/code> or the tuple <code>(\"alpha\", 0.5, 1)<\/code>?<\/p>\n<p>Post your answer in the comments below. I would love to see what you come up with.<\/p>\n<p>In the next lesson, you will learn about Python strings.<\/p>\n<h2>Lesson 04: Strings<\/h2>\n<p>In this lesson, you will learn about creating and using strings in Python.<\/p>\n<p>A string is the basic way of storing text in Python. All Python strings are unicode strings, meaning you can put unicode into it. For example:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = \"Hello <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f600.png\" alt=\"\ud83d\ude00\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\">\"\r\nprint(x)<\/pre>\n<p>The smiley is a unicode character of code point 0x1F600. Python string comes with a lot of functions. For example, we can check if a string begins or ends with a substring using:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">if x.startswith(\"Hello\"):\r\n    print(\"x starts with Hello\")\r\nif not x.endswith(\"World\"):\r\n    print(\"x does not end with World\")<\/pre>\n<p>Then to check whether a string contains a substring, use the \u201c<code>in<\/code>\u201d operator:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">if \"ll\" in x:\r\n    print(\"x contains double-l\")<\/pre>\n<p>There is a lot more. Such as <code>split()<\/code> to split a string, or <code>upper()<\/code> to convert the entire string into uppercase.<\/p>\n<p>One special property of Python strings is the <strong>implicit concatenation<\/strong>. All of the following produce the string <code>\"hello world\"<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = \"hel\" \r\n  \"lo world\"\r\nx = \"hello\" \" world\"\r\nx = (\"hello \"\r\n    \"world\")<\/pre>\n<p>The rule is, Python will normally use <code><\/code> as a line continuation. But if Python sees two strings placed together without anything separating them, the strings will be concatenated. Hence the first example above is to concatenate <code>\"hel\"<\/code> with <code>\"lo world\"<\/code>. Likewise, the last example concatenated two strings because they are placed inside parentheses.<\/p>\n<p>A Python string can also be created using a template. It is often seen in <code>print()<\/code> functions. For example, below all produce <code>\"hello world\"<\/code> for variable <code>y<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = \"world\"\r\ny = \"hello %s\" % x\r\ny = \"hello {}\".format(x)\r\ny = f\"hello {x}\"<\/pre>\n<\/p>\n<h3>Your Task<\/h3>\n<p>Try to run this code:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">coord = {\"lat\": 51.5072, \"lon\": -0.1276}\r\nprint(\"latitude %(lat)f, longitude %(lon)f\" % coord)\r\nprint(\"latitude {lat}, longitude {lon}\".format(**coord))<\/pre>\n<p>This is to fill a template using a dictionary. The first uses the <code>%<\/code>-syntax while the second uses format syntax. Can you modify the code above to print only 2 decimal places? Hints: Check out <a href=\"https:\/\/docs.python.org\/3\/library\/string.html\">https:\/\/docs.python.org\/3\/library\/string.html<\/a>!<\/p>\n<p>Post your answer in the comments below. I would love to see what you come up with.<\/p>\n<p>In the next lesson, you will discover list comprehension syntax in Python.<\/p>\n<h2>Lesson 05: List Comprehension<\/h2>\n<p>In this lesson, you will see how list comprehension syntax can build a list on the fly.<\/p>\n<p>The famous fizz-buzz problem prints 1 to 100 with all 3-multiples replaced with \u201cfizz,\u201d all 5-multiples replaced with \u201cbuzz,\u201d and if a number is both a multiple of 3 and 5, print \u201cfizzbuzz.\u201d You can make a <code>for<\/code> loop and some <code>if<\/code> statements to do this. But we can also do it in one line:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">numbers = [\"fizzbuzz\" if n%15==0 else \"fizz\" if n%3==0 else \"buzz\" if n%5==0 else str(n)\r\n          for n in range(1,101)]\r\nprint(\"n\".join(numbers))<\/pre>\n<p>We set up the list <code>numbers<\/code> using list comprehension syntax. The syntax looks like a list but with a <code>for<\/code> inside. Before the keyword <code>for<\/code>, we define how each element in the list will be created.<\/p>\n<p>List comprehension can be more complicated. For example, this is how to produce all multiples of 3 from 1 to 100:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">mul3 = [n for n in range(1,101) if n%3 == 0]<\/pre>\n<p>And this is how we can print a $10times 10$ multiplication table:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">table = [[m*n for n in range(1,11)] for m in range(1,11)]\r\nfor row in table:\r\n    print(row)<\/pre>\n<p>And this is how we can combine strings:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">directions = [a+b for a in [\"north\", \"south\", \"\"] for b in [\"east\", \"west\", \"\"] if not (a==\"\" and b==\"\")]\r\nprint(directions)<\/pre>\n<p>This prints:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">['northeast', 'northwest', 'north', 'southeast', 'southwest', 'south', 'east', 'west']<\/pre>\n<\/p>\n<h3>Your Task<\/h3>\n<p>Python also has a dictionary comprehension. The syntax is:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">double = {n: 2*n for n in range(1,11)}<\/pre>\n<p>Now try to create a dictionary <code>mapping<\/code> using dictionary comprehension that maps a string <code>x<\/code> to its length <code>len(x)<\/code> for these strings:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">keys = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]\r\nmapping = {...}<\/pre>\n<p>Post your answer in the comments below. I would love to see what you come up with.<\/p>\n<p>In the next lesson, you will discover two very useful Python functions: <code>enumerate()<\/code> and <code>zip()<\/code>.<\/p>\n<h2>Lesson 06: Enumerate and Zip<\/h2>\n<p>In this lesson, you will learn an the <code>enumerate()<\/code> function and <code>zip()<\/code> function.<\/p>\n<p>Very often, you will see you\u2019re writing a for-loop like this:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [\"alpha\", \"beta\", \"gamma\", \"delta\"]\r\nfor n in range(len(x)):\r\n    print(\"{}: {}\".format(n, x[n]))<\/pre>\n<p>But here we need the loop variable <code>n<\/code> just to use as an index to access the list <code>x<\/code>. In this case, we can ask Python to index the list while doing the loop, using <code>enumerate()<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [\"alpha\", \"beta\", \"gamma\", \"delta\"]\r\nfor n,string in enumerate(x):\r\n    print(\"{}: {}\".format(n, string))<\/pre>\n<p>The result of <code>enumerate()<\/code> produces a tuple of the counter (default starts with zero) and the element of the list. We use the unpacking syntax to set it to two variables.<\/p>\n<p>If we use the for-loop like this:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [\"blue\", \"red\", \"green\", \"yellow\"]\r\ny = [\"cheese\", \"apple\", \"pea\", \"mustard\"]\r\nfor n in range(len(x)):\r\n    print(\"{} {}\".format(x[n], y[n]))<\/pre>\n<p>Python has a function <code>zip()<\/code> to help:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [\"blue\", \"red\", \"green\", \"yellow\"]\r\ny = [\"cheese\", \"apple\", \"pea\", \"mustard\"]\r\nfor a, b in zip(x, y):\r\n    print(\"{} {}\".format(a, b))<\/pre>\n<p>The <code>zip()<\/code> function is like a zipper, taking one element from each input list and putting them side by side. You may provide more than two lists to <code>zip()<\/code>. It will produce all matching items (i.e., stop whenever it hits the end of the shortest input list).<\/p>\n<h3>Your task<\/h3>\n<p>Very common in Python programs, we may do this:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">results = []\r\nfor n in range(1, 11):\r\n    squared, cubed = n**2, n**3\r\n    results.append([n, squared, cubed])<\/pre>\n<p>Then, we can get the list of 1 to 10, the square of them, and the cube of them using <code>zip()<\/code> (note the <code>*<\/code> before <code>results<\/code> in the argument):<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">numbers, squares, cubes = zip(*results)<\/pre>\n<p>Try this out. Can you recombine <code>numbers<\/code>, <code>squares<\/code>, and <code>cubes<\/code> back to <code>results<\/code>? Hints: Just use <code>zip()<\/code>.<\/p>\n<p>In the next lesson, you will discover three more Python functions: <code>map()<\/code>, <code>filter()<\/code>, and <code>reduce()<\/code>.<\/p>\n<h2>Lesson 07: Map, Filter, and Reduce<\/h2>\n<p>In this lesson, you will learn the Python functions <code>map()<\/code>, <code>filter()<\/code>, and <code>reduce()<\/code>.<\/p>\n<p>The name of these three functions came from the functional programming paradigm. In simple terms, <code>map()<\/code> is to transform elements of a list using some function, and <code>filter()<\/code> is to short list the elements based on certain criteria. If you learned list comprehension, they are just another method of list comprehension.<\/p>\n<p>Let\u2019s consider an example we saw previously:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">def fizzbuzz(n):\r\n    if n%15 == 0:\r\n        return \"fizzbuzz\"\r\n    if n%3 == 0:\r\n        return \"fizz\"\r\n    if n%5 == 0:\r\n        return \"buzz\"\r\n    return str(n)\r\n\r\nnumbers = map(fizzbuzz, range(1,101))\r\nprint(\"n\".join(numbers))<\/pre>\n<p>Here we have a function defined, and <code>map()<\/code> uses the function as the first argument and a list as the second argument. It will take each element from a list and transform it using the provided function.<\/p>\n<p>Using <code>filter()<\/code> is likewise:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">def multiple3(n):\r\n    return n % 3 == 0\r\n\r\nmul3 = filter(multiple3, range(1,101))\r\nprint(list(mul3))<\/pre>\n<p>If that\u2019s appropriate, you can pass the return value from <code>map()<\/code> to <code>filter()<\/code> or vice versa.<\/p>\n<p>You may consider <code>map()<\/code> and <code>filter()<\/code> as another way to write list comprehension (sometimes easier to read as the logic is modularized). The <code>reduce()<\/code> function is not replaceable by list comprehension. It scans the elements from a list and combines them using a function.<\/p>\n<p>While Python has a <code>max()<\/code> function built-in, we can use <code>reduce()<\/code> for the same purpose. Note that <code>reduce()<\/code> is a function from the module <code>functools<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">from functools import reduce\r\ndef maximum(a,b):\r\n    if a &gt; b:\r\n        return a\r\n    else:\r\n        return b\r\n\r\nx = [-3, 10, 2, 5, -6, 12, 0, 1]\r\nmax_x = reduce(maximum, x)\r\nprint(max_x)<\/pre>\n<p>By default, <code>reduce()<\/code> will give the first two elements to the provided function, then the result will be passed to the function again with the third element, and so on until the input list is exhausted. But there is another way to invoke <code>reduce()<\/code>:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">x = [-3, 10, 2, 5, -6, 12, 0, 1]\r\nmax_x = reduce(maximum, x, -float(\"inf\"))\r\nprint(max_x)<\/pre>\n<p>This result is the same, but the first call to the function uses the default value (<code>-float(\"inf\")<\/code> in this case, which is negative infinity) and the first element of the list. Then uses the result and the second element from the list, and so on. Providing a default value is appropriate in some cases, such as the exercise below.<\/p>\n<h3>Your Task<\/h3>\n<p>Let\u2019s consider a way to convert a bitmap to an integer. If a list <code>[6,2,0,3]<\/code> is provided, we should consider the list as which bit to assert, and the result should be in binary, 1001101, or in decimal, 77. In this case, bit 0 is defined to be the least significant bit or the right most bit.<\/p>\n<p>We can use reduce to do this and print 77:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">def setbit(bitmap, bit):\r\n    return bitmap | (2**bit)\r\n\r\nassertbits = [6, 2, 0, 3]\r\nbitmap = reduce(setbit, assertbits, ???)\r\nprint(bitmap)<\/pre>\n<p>What should be the <code>???<\/code> above? Why?<\/p>\n<p>Post your answer in the comments below. I would love to see what you come up with.<\/p>\n<p>This was the final lesson.<\/p>\n<h2>The End!<br \/>\n(<em>Look How Far You Have Come<\/em>)<\/h2>\n<p>You made it. Well done!<\/p>\n<p>Take a moment and look back at how far you have come.<\/p>\n<p>You discovered:<\/p>\n<ul>\n<li>Python list and the slicing syntax<\/li>\n<li>Python dictionary, how to use it, and how to combine two dictionaries<\/li>\n<li>Tuples, the unpacking syntax, and how to use it to swap variables<\/li>\n<li>Strings, including many ways to create a new string from a template<\/li>\n<li>List comprehension<\/li>\n<li>The use of functions <code>enumerate()<\/code> and <code>zip()<\/code>\n<\/li>\n<li>How to use <code>map()<\/code>, <code>filter()<\/code>, and <code>reduce()<\/code>\n<\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p><strong>How did you do with the mini-course?<\/strong><br \/>\nDid you enjoy this crash course?<\/p>\n<p><strong>Do you have any questions? Were there any sticking points?<\/strong><br \/>\nLet me know. Leave a comment below.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/python-for-machine-learning-7-day-mini-course\/\">Python for Machine Learning (7-day mini-course)<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/python-for-machine-learning-7-day-mini-course\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Adrian Tam Python for Machine Learning Crash Course. Learn core Python in 7 days. Python is an amazing programming language. Not only it is [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/01\/python-for-machine-learning-7-day-mini-course\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":5667,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5666"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=5666"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5666\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/5667"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=5666"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=5666"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=5666"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}