<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Tantoluwa Heritage Alabi NB - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Tantoluwa Heritage Alabi NB - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 16:26:51 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/TantoluwaAlabiHerita/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Timer – How to Set a Timer Function in JS ]]>
                </title>
                <description>
                    <![CDATA[ In Javascript, the timer function prevents your code from running everything at once when an event triggers or the page loads. This gives you more control over the timing of your program's actions and can enhance the user experience by creating smoot... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/</link>
                <guid isPermaLink="false">66e88021ce83c61f22a00415</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Mon, 16 Sep 2024 18:59:45 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726513174015/54470912-08b3-4a23-9a0c-9b6f9b57617b.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Javascript, the timer function prevents your code from running everything at once when an event triggers or the page loads. This gives you more control over the timing of your program's actions and can enhance the user experience by creating smoother interactions or animations.  </p>
<p>In this tutorial, you'll learn how to use the set timer functions.</p>
<h2 id="heading-how-to-set-a-timer-function"><strong>How to Set a Timer Function</strong></h2>
<p>There are various ways of setting a timer function, such as the <code>setTimeout</code>, <code>setInterval</code>, <code>clearTimeout</code>, and <code>setImmediate</code> functions. You'll learn about each of them in this article.</p>
<h3 id="heading-how-to-use-settimeout-and-setinterval"><strong>How to Use</strong> <code>setTimeout</code> <strong>and</strong> <code>setInterval</code></h3>
<p>The <code>setTimeout</code> function executes an expression after a specified delay in milliseconds while the <code>setInterval</code> function executes an expression after a specified interval in milliseconds.</p>
<p>You can use the <code>setTimeout()</code> function when you want to execute code block with a specific delay, but just once.</p>
<p>The setTimeout function is denoted by <code>setTimeout()</code>. Here's an example of how you can use it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Execute a function after 3 seconds</span>
⁠ <span class="hljs-keyword">const</span> timeoutId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Timeout executed after 3 seconds'</span>);
}, <span class="hljs-number">3000</span>);
</code></pre>
<p>The above code block shows how to use the <code>setTimeout</code> syntax to execute a function after 3 seconds. The name of the variable is <code>timeoutId</code> which stores the execution of the setTimeout. The time set is 3000 milliseconds (or 3 seconds).</p>
<p>You can use the <code>setInterval()</code> function when you want to execute a code block repeatedly but at specific intervals – for instance, when animating elements.</p>
<p>The setInterval function is denoted by <code>setInterval()</code>. Here's how you can use it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Execute a function every 1 second</span>
<span class="hljs-keyword">const</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Interval executed every 1 second'</span>);
}, <span class="hljs-number">1000</span>);
</code></pre>
<p>The above code block shows how to use the <code>setInterval</code> syntax to execute a function after 1 second. The name of the variable is <code>intervalId</code> which stores the execution of the setInterval. The time is set to 1000 milliseconds (1 second).</p>
<h3 id="heading-how-to-use-cleartimeout-and-clearinterval"><strong>How to Use</strong> <code>clearTimeout</code> <strong>and</strong> <code>clearInterval</code></h3>
<p>The <code>clearTimeout</code> function cancels a timeout previously scheduled with  the <code>setTimeout</code> function. <code>clearInterval</code> cancels an interval previously set with ⁠<code>setInterval</code> .</p>
<p>The clearTimeout function is denoted by <code>clearTimeout();</code>. It accepts an argument that stores the <code>setTimeout</code> function.</p>
<p>Here's an example of how it works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timeoutId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Timeout executed after 3 seconds'</span>);
}, <span class="hljs-number">3000</span>);

<span class="hljs-built_in">clearTimeout</span>(timeoutId);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Timeout cleared'</span>);
</code></pre>
<p>The <code>clearTimeout</code> function takes the variable name <code>timeoutID</code> which stores the <code>setTimeout</code> function and clears the function.</p>
<p>The <code>clearInterval function</code> is denoted by <code>clearInterval();</code>.  It accepts an argument that stores the <code>setInterval</code> function under the block of the <code>setTimeout</code> function.</p>
<p>Here's an example of how it works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Interval executed every 1 second'</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">clearInterval</span>(intervalId);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Interval cleared. Function will no longer execute.'</span>);
}, <span class="hljs-number">5000</span>);
</code></pre>
<p>In the above code block, the <code>setTimeout</code> function is introduced. The <code>clearInterval</code> function is passed into the code block, the argument <code>intervalId</code> is passed, and then the function is executed. </p>
<p>Another timer function is <code>setImmediate</code> which executes a function asynchronously as soon as possible after the current code block finishes executing. But it’s not universally supported across all browsers, so it’s rarely used.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>It's important to know how to use JavaScript timer functions and when to apply them to your code. And remember that the timer is set to milliseconds, so whatever number you use, divide it by 1000 to determine how many seconds it is.</p>
<p>If you have any questions, you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a> 💙.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Array Length – How to Find the Length of an Array in JS ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript arrays are fundamental data structures that allow you to store and manipulate collections of elements efficiently. While working with arrays, you'll often need to know their length. The length of an array tells us how many elements are pre... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-array-length-tutorial/</link>
                <guid isPermaLink="false">66d46152182810487e0ce1ba</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Thu, 01 Feb 2024 15:56:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/pexels-venelin-dimitrov-3476312.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript arrays are fundamental data structures that allow you to store and manipulate collections of elements efficiently.</p>
<p>While working with arrays, you'll often need to know their length. The length of an array tells us how many elements are present in the array. You can use this to check if an array is empty and, if not, iterate through the elements in it.</p>
<h2 id="heading-how-to-find-the-length-of-an-array">How to Find the Length of an Array</h2>
<h3 id="heading-using-the-ltlengthgt-property">Using the <code>&lt;.length&gt;</code> property</h3>
<p>Javascript has a <code>&lt;.length&gt;</code> property that returns the size of an array as a number(integer).</p>
<p>Here's an example of how to use it:</p>
<pre><code class="lang-python">let numbers = [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>]
let numberSize = numbers.length
console.log(numberSize)
<span class="hljs-comment"># Output</span>
<span class="hljs-comment"># 4</span>
</code></pre>
<p>In the above code, a variable with the name <code>numbers</code> stores an array of numbers, while the variable <code>numberSize</code> stores the number of elements present in the array by using the method <code>.length</code>. The number size is then printed using console.log – hence the output 4.</p>
<p>Let's now check to see what the data type of the <code>length</code> property is:</p>
<pre><code class="lang-python">let numbers = [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>]
let numberSize = numbers.length
console.log(typeof numberSize)
<span class="hljs-comment"># Output</span>
<span class="hljs-comment"># number</span>
</code></pre>
<p>In the above code we see that the output is <code>number</code>.</p>
<p>Here's an example of how to access an array element with the <code>length</code> property in a for loop:</p>
<pre><code class="lang-python">let numbers = [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>]
<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++){
   console.log(numbers[i]);
}
<span class="hljs-comment"># Output</span>
<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 13</span>
<span class="hljs-comment"># 14</span>
<span class="hljs-comment"># 25</span>
</code></pre>
<h3 id="heading-without-using-the-length-method">Without Using the <code>.length()</code> method</h3>
<p>In this method, we will iterate through the elements and count each of the elements present in the array.</p>
<p>Here's how it works:</p>
<pre><code class="lang-python">function arrayLength(arr) {
   let count = <span class="hljs-number">0</span>;
   <span class="hljs-keyword">for</span> (const element of arr) {
     count++;
   }

   <span class="hljs-keyword">return</span> count; 
}
let numbers = [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>]
console.log(<span class="hljs-string">"Length of array:"</span>, arrayLength(numbers));
<span class="hljs-comment"># Output</span>
<span class="hljs-comment"># Length of array: 4</span>
</code></pre>
<p>In the above code, there's a function named <code>arrayLength</code> that accepts the array as input. We created a variable called <code>count</code> that is assigned 0. The <code>count</code> variable will store the count of the number of elements in the array.</p>
<p>To count the elements in the array, we used a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for-of loop</a> to check each element in the array.</p>
<p>The code iterates over each element in the array until undefined is encountered. That is, we iterate over each element in the array until we reach the end of the array where there are no more elements to check. Finally we return <code>count</code> as the output.</p>
<p>We pass in the variable <code>&lt;numbers&gt;</code> as the input to the function in order to obtain the length of the array as the returned value.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The most common and straightforward method is to use the length property of the array. But you can also use a longer method by looping through the array. These methods allow you to work with arrays of different sizes and types.</p>
<p>If you have any questions, you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a> 💙.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Requirements.txt – How to Create and Pip Install Requirements.txt in Python ]]>
                </title>
                <description>
                    <![CDATA[ There are many Python packages we use to solve our coding problems daily. Take, for instance, the library "Beautiful Soup," – it doesn't come with Python by default and needs to be installed separately. Many projects rely on libraries and other depen... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-requirementstxt-explained/</link>
                <guid isPermaLink="false">66d461543a8352b6c5a2ab21</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Mon, 11 Sep 2023 14:17:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/pexels-christina-morillo-1181671--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are many Python packages we use to solve our coding problems daily. Take, for instance, the library "Beautiful Soup," – it doesn't come with Python by default and needs to be installed separately.</p>
<p>Many projects rely on libraries and other dependencies, and installing each one can be tedious and time-consuming.</p>
<p>This is where a ‘requirements.txt’ file comes into play. requirements.txt is a file that contains a list of packages or libraries needed to work on a project that can all be installed with the file. It provides a consistent environment and makes collaboration easier.</p>
<h2 id="heading-format-of-a-requirementstxt-file">Format of a requirements.txt File</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-219.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Diagram showing a box containing requirements.txt and another box below it containing the text "package_name == version"</em></p>
<p>The above image shows a sample of a created requirements.txt file, containing a list of packages and versions of the installation.</p>
<h2 id="heading-key-terms">Key Terms</h2>
<p>I've mentioned a few terms so far that you may not know. Here's what they mean, along with some other important terms you'll come across when working with requirements.txt:</p>
<ul>
<li><p><strong>Dependencies</strong> are software components that a program needs to run correctly. They can be libraries, frameworks, or other programs.</p>
</li>
<li><p><strong>Packages</strong> are a way to group together related dependencies. They make it easier to install and manage dependencies.</p>
</li>
<li><p><strong>Virtual Environments</strong> is a directory that contains a copy of the Python interpreter and all of the packages that are required for a particular project.</p>
</li>
<li><p><strong>Pip:</strong> This is a package manager for Python. You can use Pip to install, uninstall, and manage Python packages.</p>
</li>
</ul>
<h2 id="heading-how-to-create-a-requirementstxt-file">How to Create a requirements.txt File</h2>
<p>To create a requirements file, you must set up your virtual environment. If you use Pycharm, there's a virtual environment already setup (.venv). But with Visual Studio code, you have to create <a target="_blank" href="https://code.visualstudio.com/docs/python/environments">the virtual environment</a> yourself.</p>
<p>You can use your terminal or command prompt to create your requirements file. These are the steps to follow when creating the file:</p>
<p>First, open your terminal or command prompt. Then check to see if the file path shown is your working directory. Use the following command to do that:</p>
<pre><code class="lang-python">$ cd folder-name <span class="hljs-comment">#cd - change directory</span>
</code></pre>
<p>In the command above, replace ‘folder-name’ with the directory name you want to access.</p>
<p><img src="https://lh4.googleusercontent.com/vgAz2y8K2iS5wT805qSCN4GhJSv4CDu_eY1_lD_xjetaHhqkNIIvZfCmlVBmBfYYw3PrEYlkq2lasDFsc3YhMtqxZwP4AVn3P70820VeUPdVZxVXU8Cw_UNqPhKnKn3fqpy1sgC5UY4urtfqj4VlYcg" alt="Image" width="1600" height="903" loading="lazy"></p>
<p><em>Diagram showing set project directory on command line</em></p>
<p>Next, run this command:</p>
<pre><code class="lang-python">$ pip freeze &gt; requirements.txt
</code></pre>
<p>And you'll see that the requirements file gets added</p>
<p><strong>Here's the output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/requirementfile.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Diagram showing the newly created requirements file</em></p>
<p>And here's your newly created requirements.txt file:</p>
<p><img src="https://lh5.googleusercontent.com/1NEE23GJuy_i0qdANdi6twSQGnjfHrjVZ6LuUlENe57kqsMoUve3W0WcmxZLfY9JW04GrYZghVWFtY4_LnVU-isHVxv0ySpMCDQ5sYwhw2BhlQjCLbj2oa_v_nMIUgar2xayjkPRj6ogUARpZEYtKiA" alt="Image" width="1600" height="884" loading="lazy"></p>
<p><em>Diagram showing lists of packages in requirements file</em></p>
<p>The image above shows the dependencies you can work with along with their versions.</p>
<h2 id="heading-how-to-work-with-a-requirementstxt-file">How to Work with a requirements.txt File</h2>
<p>Now that we have the requirements file, you can see that it consists of a long list of different packages.</p>
<p>To work with the packages, you have to install them. You can do this by using the command prompt or terminal.</p>
<p>Type this command:</p>
<pre><code class="lang-python">pip install -r requirements.txt
</code></pre>
<p>It will look like this:</p>
<p><img src="https://lh3.googleusercontent.com/7FDCFqn38aY2GFcoqtrKyy4Oyu_8cAPdJkOxbUIdZTfSalvufWIrbEehT61tgJxuhqiA0nINSfkyHcbE-H-H-hc77rY1zTkMQhyRijtWBOEqcaWZL7fnyNxRDO1hmKcagc9sYI4qijgj6Ut2lVY-zto" alt="Image" width="1600" height="900" loading="lazy"></p>
<p><em>Image showing installation of packages present in requirements.txt file</em></p>
<p>Now that all the dependencies are installed, you can work with requirements.txt.</p>
<h3 id="heading-example-of-using-requirementstxt">Example of using requirements.txt</h3>
<p>In this example, we will be working with two libraries, <code>beautifulsoup4</code> and <code>requests</code>, to return some information from a site.</p>
<p><img src="https://lh6.googleusercontent.com/M5xLixBqsvL-vtUPFwEZq7NzB-jJDSpycapgv22OxtBKRFa9ysE0kIIPSG0mjltzfknNMdtlPYC8xDWwVnNyGiURQxHFJCrMI_Axexn7dKMRfVN4qUHLt0TEojj_pbLMW-cz_9wlrVw6VOOr8MaD-uQ" alt="Image" width="1600" height="387" loading="lazy"></p>
<p><em>Diagram showing the working libraries for this example in the requirements file</em></p>
<p>In the image above, we see that the two libraries are present in the requirements.txt file and their version. Now we can work with the libraries because we installed them previously.</p>
<ul>
<li>Import the library BeautifulSoup from the package name bs4 (beautifulsoup4) and also import the library requests.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
<span class="hljs-keyword">import</span> requests
</code></pre>
<ul>
<li>To fetch information from the website URL, we use the <code>.get()</code> method to tap into the requests library.</li>
</ul>
<pre><code class="lang-python">web_data = requests.get(<span class="hljs-string">"https://www.lithuania.travel/en/category/what-is-lithuania"</span>, headers={<span class="hljs-string">"User-Agent"</span>: <span class="hljs-string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"</span>})
</code></pre>
<ul>
<li>Now that we have access to the the URL, the Beautiful Soup library accepts the <code>web_data</code> and returns all HTML contents present in it.</li>
</ul>
<pre><code class="lang-python">soup = BeautifulSoup(web_data.content, features=<span class="hljs-string">"html.parser"</span>)
</code></pre>
<ul>
<li><p>The final result I chose to return is elements with the</p>
<p>  tag in the first position [0].</p>
</li>
</ul>
<pre><code class="lang-python">news_info = soup.findAll(<span class="hljs-string">"p"</span>)[<span class="hljs-number">0</span>]
print(news_info.text
</code></pre>
<p>Bringing it all together:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
<span class="hljs-keyword">import</span> requests
web_data = requests.get(<span class="hljs-string">"https://www.lithuania.travel/en/category/what-is-lithuania"</span>, headers={<span class="hljs-string">"User-Agent"</span>: <span class="hljs-string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"</span>})
soup = BeautifulSoup(web_data.content, features=<span class="hljs-string">"html.parser"</span>)
news_info = soup.findAll(<span class="hljs-string">"p"</span>)[<span class="hljs-number">0</span>]
print(news_info.text)
</code></pre>
<p>And here's the output:</p>
<p><img src="https://lh4.googleusercontent.com/4H_qTUMuvWXNGMKpGrxHfVY6WaEntz51xZ936GwYWY6JRXILVPyd06spEt6emH0XKajK3Ov0qLixzgrqtEC5cIr-81UxyB61fTPPNhGcDc5eEhVoateHzmpAnvowdtbkqJgdz7IlpZ2aGtv9OWLCUCA" alt="Image" width="1600" height="854" loading="lazy"></p>
<p><em>Diagram showing code and result</em></p>
<h2 id="heading-benefits-of-using-a-requirementstxt-file">Benefits of Using a requirements.txt File</h2>
<ul>
<li><p>Managing dependencies: By listing the dependencies of your project in a requirements.txt file, you can easily see what packages are required and what versions they need to be.</p>
</li>
<li><p>Sharing your project with others: If you share your project with others, you can include the requirements.txt file so that they can easily install the required packages. This can save them time and frustration and can help to ensure that everyone is using the same versions of the packages.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In the article, we learned how to create a requirements.txt file and outlined the benefits of using it.</p>
<p>You should also try it out and work on a few projects with it. If you have any questions, you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a> 💙.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Greedy Algorithm? Examples of Greedy Algorithms ]]>
                </title>
                <description>
                    <![CDATA[ According to the Oxford English Dictionary, "greedy" means having excessive desire for something without considering the effect or damage done. In computer science, a greedy algorithm is an algorithm that finds a solution to problems in the shortest ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/greedy-algorithms/</link>
                <guid isPermaLink="false">66d4614e38f2dc3808b7910b</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Fri, 12 May 2023 17:57:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/pexels-pixabay-206627.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>According to the Oxford English Dictionary, "greedy" means having excessive desire for something without considering the effect or damage done.</p>
<p>In computer science, a greedy algorithm is an algorithm that finds a solution to problems in the shortest time possible. It picks the path that seems optimal at the moment without regard for the overall optimization of the solution that would be formed.</p>
<p>Edsger Dijkstra, a computer scientist and mathematician who wanted to calculate a minimum spanning tree, introduced the term "Greedy algorithm". Prim and Kruskal came up with optimization techniques for minimizing cost of graphs.</p>
<p>Many Greedy algorithms were developed to solve graph problems. A graph is a structure made up of edges and vertices.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/simple-graph-diagram.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Diagram of a simple graph</em></p>
<h2 id="heading-greedy-vs-not-greedy-algorithms">Greedy vs Not Greedy Algorithms</h2>
<p>An algorithm is greedy when the path picked is regarded as the best option based on a specific criterion without considering future consequences. But it typically evaluates feasibility before making a final decision. The correctness of the solution depends on the problem and criteria used.</p>
<p>Example: A graph has various weights and you are to determine the maximum value in the tree. You'd start by searching each node and checking its weight to see if it is the largest value.</p>
<p>There are two approaches to solving this problem: greedy approach or not greedy.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/example-graph.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example graph</em></p>
<p>This graph consists of different weights and we need to find the maximum value. We'll apply the two approaches on the graph to get the solution.</p>
<h3 id="heading-greedy-approach">Greedy Approach</h3>
<p>In the images below, a graph has different numbers in its vertices and the algorithm is meant to select the vertex with the largest number.</p>
<p>Starting from vertex 6, then it's faced with two decisions – which is bigger, 3 or 4? The algorithm picks 4, and then is faced with another decision – which is bigger, 14 or 11. It selects 14, and the algorithm ends.</p>
<p>On the other hand there is a vertex labeled 20 but it is attached to vertex 3 which greedy does not consider as the best choice. It is important to select appropriate criteria for making each immediate decision.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/greedy-approach-graph.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The sample graph showing the greedy approach</em></p>
<h3 id="heading-not-greedy-approach">Not Greedy Approach</h3>
<p>The “not greedy” approach checks all options before arriving at a final solution, unlike the "greedy approach" which stops once it gets its results.</p>
<p>Starting from vertex 6, then it's faced with two decisions – which is bigger, 3 or 4? The algorithm picks 4, and then is faced with another decision – which is bigger, 14 or 11. It selects 14 and keeps it aside.</p>
<p>Then it runs the process again, starting from vertex 6. It selects the vertex with 3 and checks it. 20 is attached to the vertex 3 and the process stops. Now it compares the two results – 20 and 14. 20 is bigger, so it selects the vertex (3) that carries the largest number and the process ends.</p>
<p>This approach considers many possibilities in finding the better solution.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/non-greedy-approach-graph.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The sample graph showing the non-greedy approach</em></p>
<h2 id="heading-characteristics-of-a-greedy-algorithm">Characteristics of a Greedy Algorithm</h2>
<ul>
<li><p>The algorithm solves its problem by finding an optimal solution. This solution can be a maximum or minimum value. It makes choices based on the best option available.</p>
</li>
<li><p>The algorithm is fast and efficient with time complexity of O(n log n) or O(n). Therefore applied in solving large-scale problems.</p>
</li>
<li><p>The search for optimal solution is done without repetition – the algorithm runs once.</p>
</li>
<li><p>It is straightforward and easy to implement.</p>
</li>
</ul>
<h2 id="heading-how-to-use-greedy-algorithms">How to Use Greedy Algorithms</h2>
<p>Before applying a greedy algorithm to a problem, you need to ask two questions:</p>
<ul>
<li><p>Do you need the best option at the moment from the problem?</p>
</li>
<li><p>Do you need an optimal solution (either minimum or maximum value)?</p>
</li>
</ul>
<p>If your answer to these questions is "Yes", then a greedy algorithm is a good choice to solve your problem.</p>
<h3 id="heading-procedure">Procedure</h3>
<p>Let’s assume you have a problem with a set of numbers and you need to find the minimum value.</p>
<p>You start of by defining the constraint, which in this case is finding the minimum value. Then each number will be scanned and checked on each constraint which serves as a condition to be fulfilled. If the condition is true, the number(s) is selected and returned as the final solution.</p>
<p>Here's a flowchart representation of this process:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/greedy-algorithm-flow-chart.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flow chart showing the process for solving a problem using greedy algorithms</em></p>
<h2 id="heading-greedy-algorithm-examples">Greedy Algorithm Examples</h2>
<h3 id="heading-problem-1-activity-selection-problem">Problem 1 : Activity Selection Problem</h3>
<p>This problem contains a set of activities or tasks that need to be completed. Each one has a start and finish time. The algorithm finds the maximum number of activities that can be done in a given time without them overlapping.</p>
<h3 id="heading-approach-to-the-problem">Approach to the Problem</h3>
<ul>
<li><p>We have a list of activities. Each has a start time and finish time.</p>
</li>
<li><p>First, we sort the activities and start time in ascending order using the finish time of each.</p>
</li>
<li><p>Then we start by picking the first activity. We create a new list to store the selected activity.</p>
</li>
<li><p>To choose the next activity, we compare the finish time of the last activity to the start time of the next activity. If the start time of the next activity is greater than the finish time of the last activity, it can be selected. If not we skip this and check the next one.</p>
</li>
<li><p>This process is repeated until all activities are checked. The final solution is a list containing the activities that can be done.</p>
</li>
</ul>
<p>The table below shows a list of activities as well as starting and finish times.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/start-and-finish-times-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The first step is to sort the finish time in ascending order and arrange the activities with respect to the result.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/start-and-finish-times-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After sorting the activities, we select the first activity and store it in the selected activity list. In our example, the first activity is “Homework”.</p>
<p>Moving to the next activity, we check the finish time of “Homework” (5) which was the last activity selected and the starting time of “Term paper” (4). To pick an activity, the starting time of the next activity must be greater than or equal to the finish time. (4) is less than (5), so we skip the activity and move to the next.</p>
<p>The next activity “Presentation” has a starting time of (6) and it is greater than the finish time (5) of “Homework”. So we select it and add it to our list of selected activities.</p>
<p>For the next activity, we do the same checking. Finish time of “Presentation” is (10), starting time of “Volleyball practice ” is (10). We see that the starting time is equal to the finish time which satisfies one of the conditions, so we select it and add it to our list of selected activities.</p>
<p>Continuing to the next activity, the finish time of “Volleyball” practice is (12) and the starting time of “Biology lecture” is (13). We see the starting time is greater than the finish time so we select it.</p>
<p>For our last activity, the starting time for “Hangout” is (7) and the finishing time of our last activity “Biology lecture” is (14), 7 is less than 14, so we cannot select the activity. Since we are at the end of our activity list, the process ends.</p>
<p>Our final result is the list of selected activities that we can do without time overlapping: {Homework, Presentation, Volleyball practice, Biology lecture}.</p>
<h3 id="heading-code-implementation-of-the-example">Code Implementation of the Example</h3>
<p>The variable <code>&lt;data&gt;</code> stores the starting times of each activity, the finish time of each activity, and the list of tasks (or activities) to be performed.</p>
<p>The variable <code>&lt;selected_activity&gt;</code> is an empty list that will store the selected activities that can be performed.</p>
<p><code>&lt;start_position&gt;</code> shows the position the first activity which is index “0”. This will be our starting point.</p>
<pre><code class="lang-python">data = {
  <span class="hljs-string">"start_time"</span>: [<span class="hljs-number">2</span> , <span class="hljs-number">6</span> , <span class="hljs-number">4</span> , <span class="hljs-number">10</span> , <span class="hljs-number">13</span> , <span class="hljs-number">7</span>],
  <span class="hljs-string">"finish_time"</span>: [<span class="hljs-number">5</span> , <span class="hljs-number">10</span> , <span class="hljs-number">8</span> , <span class="hljs-number">12</span> , <span class="hljs-number">14</span> , <span class="hljs-number">15</span>],
  <span class="hljs-string">"activity"</span>: [<span class="hljs-string">"Homework"</span> , <span class="hljs-string">"Presentation"</span> , <span class="hljs-string">"Term paper"</span> , <span class="hljs-string">"Volleyball practice"</span> , <span class="hljs-string">"Biology lecture"</span> , <span class="hljs-string">"Hangout"</span>]
}

selected_activity =[]
start_position = <span class="hljs-number">0</span>
</code></pre>
<p>Here's a dataframe table showing the original data:</p>
<pre><code class="lang-python">Original Info

   start_time  finish_time             activity
<span class="hljs-number">0</span>           <span class="hljs-number">2</span>            <span class="hljs-number">5</span>             Homework
<span class="hljs-number">1</span>           <span class="hljs-number">6</span>           <span class="hljs-number">10</span>         Presentation
<span class="hljs-number">2</span>           <span class="hljs-number">4</span>            <span class="hljs-number">8</span>           Term paper
<span class="hljs-number">3</span>          <span class="hljs-number">10</span>           <span class="hljs-number">12</span>  Volleyball practice
<span class="hljs-number">4</span>          <span class="hljs-number">13</span>           <span class="hljs-number">14</span>      Biology lecture
<span class="hljs-number">5</span>           <span class="hljs-number">7</span>           <span class="hljs-number">15</span>              Hangout
</code></pre>
<p>Then we sort the finish time in ascending order and rearrange the start time and activity in respect to it. We target the variables by using the keys in the dictionary.</p>
<pre><code class="lang-python">tem = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span> , len(data[<span class="hljs-string">'finish_time'</span>])):
   <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span> , len(data[<span class="hljs-string">'finish_time'</span>])):
       <span class="hljs-keyword">if</span> data[<span class="hljs-string">'finish_time'</span>][i] &lt; data[<span class="hljs-string">'finish_time'</span>][j]:
           tem = data[<span class="hljs-string">'activity'</span>][i] , data[<span class="hljs-string">'finish_time'</span>][i] , data[<span class="hljs-string">'start_time'</span>][i]
           data[<span class="hljs-string">'activity'</span>][i] , data[<span class="hljs-string">'finish_time'</span>][i] , data[<span class="hljs-string">'start_time'</span>][i] = data[<span class="hljs-string">'activity'</span>][j] , data[<span class="hljs-string">'finish_time'</span>][j] , data[<span class="hljs-string">'start_time'</span>][j]
           data[<span class="hljs-string">'activity'</span>][j] , data[<span class="hljs-string">'finish_time'</span>][j] , data[<span class="hljs-string">'start_time'</span>][j] = tem
</code></pre>
<p>In the code above, we intialized <code>&lt;tem&gt;</code> to zero. We are not using the inbuilt method to sort the finish time. We are using two loops to arrange it in ascending order. <code>&lt;i&gt;</code> and <code>&lt;j&gt;</code> represent the indexes and check if values of the <code>&lt;data['finish_time'][i]&gt;</code> is less than <code>&lt;data['finish_time'][j]&gt;</code>.</p>
<p>If the condition is true, <code>&lt;tem&gt;</code> stores the values of the elements in the <code>&lt;i&gt;</code> position and swaps the corresponding element.</p>
<p>Now we print the final result, here's what we get:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Start time: "</span> , data[<span class="hljs-string">'start_time'</span>])
print(<span class="hljs-string">"Finish time: "</span> , data[<span class="hljs-string">'finish_time'</span>])
print(<span class="hljs-string">"Activity: "</span> , data[<span class="hljs-string">'activity'</span>])

<span class="hljs-comment"># Results before sorting</span>
<span class="hljs-comment"># Start time:  [2, 6, 4, 10, 13, 7]</span>
<span class="hljs-comment"># Finish time:  [5, 10, 8, 12, 14, 15]</span>
<span class="hljs-comment"># Activity:  ['Homework', 'Presentation', 'Term paper', 'Volleyball practice', 'Biology lecture', 'Hangout']</span>


<span class="hljs-comment"># Results after sorting</span>
<span class="hljs-comment"># Start time:  [2, 4, 6, 10, 13, 7]</span>
<span class="hljs-comment"># Finish time:  [5, 8, 10, 12, 14, 15]</span>
<span class="hljs-comment"># Activity:  ['Homework', 'Term paper', 'Presentation', 'Volleyball practice', 'Biology lecture', 'Hangout']</span>
</code></pre>
<p>And here's a dataframe table showing the sorted data:</p>
<pre><code class="lang-python">Sorted Info <span class="hljs-keyword">with</span> respect to finish_time

   start_time  finish_time             activity
<span class="hljs-number">0</span>       <span class="hljs-number">2</span>            <span class="hljs-number">5</span>             Homework
<span class="hljs-number">1</span>       <span class="hljs-number">4</span>            <span class="hljs-number">8</span>           Term paper
<span class="hljs-number">2</span>       <span class="hljs-number">6</span>           <span class="hljs-number">10</span>         Presentation
<span class="hljs-number">3</span>          <span class="hljs-number">10</span>           <span class="hljs-number">12</span>       Volleyball practice
<span class="hljs-number">4</span>          <span class="hljs-number">13</span>           <span class="hljs-number">14</span>         Biology lecture
<span class="hljs-number">5</span>       <span class="hljs-number">7</span>           <span class="hljs-number">15</span>          Hangout
</code></pre>
<p>After sorting the activities, we start by selecting the first activity, which is “Homework”. It has a starting index of “0” so we use the <code>&lt;start_position&gt;</code> to target the activity and append it to the empty list.</p>
<pre><code class="lang-python">selected_activity.append(data[<span class="hljs-string">'activity'</span>][start_position])
</code></pre>
<p>The condition for selecting an activity is that the start time of the next activity selected is greater than the finish time of the previous activity. If the condition is true, the selected activity is added to the <code>&lt;selected_activity&gt;</code> list.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> pos <span class="hljs-keyword">in</span> range(len(data[<span class="hljs-string">'finish_time'</span>])):
   <span class="hljs-keyword">if</span> data[<span class="hljs-string">'start_time'</span>][pos] &gt;= data[<span class="hljs-string">'finish_time'</span>][start_position]:
       selected_activity.append(data[<span class="hljs-string">'activity'</span>][pos])
       start_position = pos

print(<span class="hljs-string">f"The student can work on the following activities: <span class="hljs-subst">{selected_activity}</span>"</span>)

<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># The student can work on the following activities: ['Homework', 'Presentation', 'Volleyball practice', 'Biology lecture']</span>
</code></pre>
<p>Here's what it looks like all together:</p>
<pre><code class="lang-python">data = {
  <span class="hljs-string">"start_time"</span>: [<span class="hljs-number">2</span> , <span class="hljs-number">6</span> , <span class="hljs-number">4</span> , <span class="hljs-number">10</span> , <span class="hljs-number">13</span> , <span class="hljs-number">7</span>],
  <span class="hljs-string">"finish_time"</span>: [<span class="hljs-number">5</span> , <span class="hljs-number">10</span> , <span class="hljs-number">8</span> , <span class="hljs-number">12</span> , <span class="hljs-number">14</span> , <span class="hljs-number">15</span>],
  <span class="hljs-string">"activity"</span>: [<span class="hljs-string">"Homework"</span> , <span class="hljs-string">"Presentation"</span> , <span class="hljs-string">"Term paper"</span> , <span class="hljs-string">"Volleyball practice"</span> , <span class="hljs-string">"Biology lecture"</span> , <span class="hljs-string">"Hangout"</span>]
}

selected_activity =[]
start_position = <span class="hljs-number">0</span>
<span class="hljs-comment"># sorting the items in ascending order with respect to finish time</span>
tem = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span> , len(data[<span class="hljs-string">'finish_time'</span>])):
   <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span> , len(data[<span class="hljs-string">'finish_time'</span>])):
       <span class="hljs-keyword">if</span> data[<span class="hljs-string">'finish_time'</span>][i] &lt; data[<span class="hljs-string">'finish_time'</span>][j]:
           tem = data[<span class="hljs-string">'activity'</span>][i] , data[<span class="hljs-string">'finish_time'</span>][i] , data[<span class="hljs-string">'start_time'</span>][i]
           data[<span class="hljs-string">'activity'</span>][i] , data[<span class="hljs-string">'finish_time'</span>][i] , data[<span class="hljs-string">'start_time'</span>][i] = data[<span class="hljs-string">'activity'</span>][j] , data[<span class="hljs-string">'finish_time'</span>][j] , data[<span class="hljs-string">'start_time'</span>][j]
           data[<span class="hljs-string">'activity'</span>][j] , data[<span class="hljs-string">'finish_time'</span>][j] , data[<span class="hljs-string">'start_time'</span>][j] = tem

<span class="hljs-comment"># by default, the first activity is inserted in the list of activities to be selected.</span>

selected_activity.append(data[<span class="hljs-string">'activity'</span>][start_position])
<span class="hljs-keyword">for</span> pos <span class="hljs-keyword">in</span> range(len(data[<span class="hljs-string">'finish_time'</span>])):
   <span class="hljs-keyword">if</span> data[<span class="hljs-string">'start_time'</span>][pos] &gt;= data[<span class="hljs-string">'finish_time'</span>][start_position]:
       selected_activity.append(data[<span class="hljs-string">'activity'</span>][pos])
       start_position = pos

print(<span class="hljs-string">f"The student can work on the following activities: <span class="hljs-subst">{selected_activity}</span>"</span>)
<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># The student can work on the following activities: ['Homework', 'Presentation', 'Volleyball practice', 'Biology lecture']</span>
</code></pre>
<h3 id="heading-problem-2-fractional-knapsack-problem">Problem 2: Fractional Knapsack Problem</h3>
<p>A knapsack has a maximum weight, and it can only accommodate a certain set of items. These items have a weight and a value.</p>
<p>The aim is to fill the knapsack with the items that have the highest total values and do not exceed the maximum weight capacity.</p>
<h3 id="heading-approach-to-the-problem-1">Approach to the Problem</h3>
<p>There are two elements to consider: the knapsack and the items. The knapsack has a maximum weight and carries some items with a high value.</p>
<p><strong>Scenario:</strong> In a jewelry store, there are items made of gold, silver, and wood. The costliest item is gold followed by silver and then wood. If a jewerly thief comes to the store, they take gold because they will make the most profit.</p>
<p>The thief has a bag (knapsack) that they can put those items in. But there is a limit to what the thief can carry because these items can get heavy. The idea is to pick the item the makes the highest profit and fits in the bag (knapsack) without exceeding its maximum weight.</p>
<ul>
<li><p>The first step is to find the value to weight ratio of all items to know what fraction each one occupies.</p>
</li>
<li><p>We then sort these ratios in descending order (from highest to lowest ). This way we can pick the ratios with the highest number first knowing that we will make a profit.</p>
</li>
<li><p>When we pick the highest ratio, we find the corresponding weight and add it to the knapsack. There are conditions to be checked.</p>
</li>
</ul>
<p><strong>Condition 1</strong>: If the item added has a lesser weight than the maximum weight of the knapsack, more items are added until the sum of all the items in the bag are the same as the maximum weight of the knapsack.</p>
<p><strong>Condition 2</strong>: If the sum of the items’ weight in the bag is more than the maximum capacity of the knapsack, we find the fraction of the last item added. To find the fraction, we do the following:</p>
<ul>
<li><p>We find the sum of the remaining weights of the items in the knapsack. They must be less than the maximum capacity.</p>
</li>
<li><p>We find the difference between the maximum capacity of the knapsack and the sum of the remaining weights of the items and divide by the weight of the last item to be added.</p>
</li>
</ul>
<pre><code class="lang-python">Fraction =  (maximum capacity of the knapsack - sum of remaining weights) / weight of last item to be added
</code></pre>
<p>To add the weight of the last item to the knapsack, we multiply the fraction by the weight.</p>
<pre><code class="lang-python">Weight_added = weight of last item to be added  * fraction
</code></pre>
<p>When we sum up the weights of all the items it will be equal to the knapsack's maximum weight.</p>
<h3 id="heading-practical-example">Practical Example:</h3>
<p>Let's say that the maximum capacity of the knapsack is 17, and there are three items available. The first item is gold, the second item is silver, and third item is wood.</p>
<ul>
<li><p>Weight of gold is 10, the weight of silver is 6, and the weight of wood is 2</p>
</li>
<li><p>the value (profit) of gold is 40, the value (profit) of silver is 30, and the value (profit) of wood is 6.</p>
</li>
<li><p>Ratio of gold= value/weight = 40/10 = 4</p>
</li>
<li><p>Ratio of silver = value/weight=30/6 = 5</p>
</li>
<li><p>Ratio of wood = value/weight = 6/2 = 3</p>
</li>
<li><p>Arranging the ratios in descending: 5, 4, 3.</p>
</li>
<li><p>The largest ratio is 5 and we match it to the corresponding weight “6”. It points to silver.</p>
</li>
<li><p>We put silver in the knapsack first and compare it to the maximum weight which is 17. 6 is less than 17 so we have to add another item. Going back to the ratios, the second largest is “4” and it corresponds to the weight of “10” which points to gold.</p>
</li>
<li><p>Now, we put gold in the knapsack, add the weight of the silver and gold, and compare it with the knapsack weight. (6 + 10 = 16). Checking it against the maximum weight, we see that it is less. So we can take another item. We go back to the list of ratios and take the 3rd largest which is “3” and it corresponds to “2” which points to wood.</p>
</li>
<li><p>When we add wood in the knapsack, the total weight is (6 +10+2 = 18) but that is greater than our maximum weight which is 17. We take out the wood from the knapsack and we are left with gold and silver. The total sum of the two is 16 and the maximum capacity is 17. So we need a weight of 1 to make it equal. Now we apply condition 2 discussed above to find the fraction of wood to fit in the knapsack.</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/frac1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Explanation of filling the remaining space in the backpack with a fractional piece of wood</em></p>
<p>Now the knapsack is filled.</p>
<h3 id="heading-code-implementation-of-the-example-1">Code Implementation of the Example</h3>
<p>The variable <code>&lt;data&gt;</code> stores the weights of each item and the profits. The variable <code>&lt;maximum_capacity&gt;</code> stores the maximum weight of the knapsack. <code>&lt;selected_wt&gt;</code> is intialized at 0, and it will store the selected weights to be put in the knapsack. Lastly, <code>&lt;max_profit&gt;</code> is intialized as 0, it will store the values of the selected weight.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"weight"</span>: [<span class="hljs-number">10</span> , <span class="hljs-number">6</span> , <span class="hljs-number">2</span>],
    <span class="hljs-string">"profit"</span>:[<span class="hljs-number">40</span> , <span class="hljs-number">30</span> ,<span class="hljs-number">6</span>]
}
max_weight = <span class="hljs-number">17</span>
selected_wt = <span class="hljs-number">0</span>
max_profit = <span class="hljs-number">0</span>
</code></pre>
<p>Then we calculate the ratio of the profit to the weight. Ratio = profit/weight:</p>
<pre><code class="lang-python">ratio = [int(data[<span class="hljs-string">'profit'</span>][i] / data[<span class="hljs-string">'weight'</span>][i]) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(data[<span class="hljs-string">'profit'</span>]))]
</code></pre>
<p>Now that we have the ratio, we arrange the elements in descending order, from biggest to smallest. Then the items in weight and profit are arranged according to the positions of the sorted ratio.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(ratio)):
    <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(i + <span class="hljs-number">1</span> , len(ratio)):
        <span class="hljs-keyword">if</span> ratio[i] &lt; ratio[j]:
            ratio[i] , ratio[j] = ratio[j] , ratio[i]
            data[<span class="hljs-string">'weight'</span>][i] , data[<span class="hljs-string">'weight'</span>][j] = data[<span class="hljs-string">'weight'</span>][j] , data[<span class="hljs-string">'weight'</span>][i]
            data[<span class="hljs-string">'profit'</span>][i] , data[<span class="hljs-string">'profit'</span>][j] = data[<span class="hljs-string">'profit'</span>][j] , data[<span class="hljs-string">'profit'</span>][i]
</code></pre>
<p>After the weight and profit are sorted, we start choosing the items and checking the condition. We loop through the length of ratio to target the index of each item in the list. Note: all items in ratio are arranged from biggest to smallest, so the first item is the maximum value and the last item is the minimum value.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(ratio)):
</code></pre>
<p>The first item we select has the highest ratio amongst the rest and it is in index 0. Now that the first weight is selected weight, we check if it is less than maximum weight. If it is, we add items till the total weight is equal to the weight of the knapsack. The second item we select has the second highest ratio amongst the rest and it is in index 1, the arrangement is that order of selection.</p>
<p>For every selected weight, we add it to the <code>selected_wt</code> variable and their corresponding profits to the <code>max_profit</code> variable.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> selected_wt + data[<span class="hljs-string">'weight'</span>][i] &lt;= max_weight:
          selected_wt += data[<span class="hljs-string">'weight'</span>][i]
          max_profit += data[<span class="hljs-string">'profit'</span>][i]
</code></pre>
<p>When the sum of the selected weights in the knapsack exceeds the maximum weight, we find the fraction of the weight of the last item added to make the total selected weights be equal to the maximum weight. We do this by finding the difference between the <code>max_weight</code> and the sum of the selected weights divided by the weight of the last item added.</p>
<p>The final profit made from the fraction carried is added to the <code>max_profit</code> variable. Then we return the <code>max_profit</code> as the final result.</p>
<pre><code class="lang-python">      <span class="hljs-keyword">else</span>:
          frac_wt = (max_weight - selected_wt) / data[<span class="hljs-string">'weight'</span>][i]
          frac_value = data[<span class="hljs-string">'profit'</span>][i] * frac_wt
          max_profit += frac_value
          selected_wt += (max_weight - selected_wt)
print(max_profit)
</code></pre>
<p>Bringing it all together:</p>
<pre><code class="lang-python">
data = {
    <span class="hljs-string">"weight"</span>: [<span class="hljs-number">10</span> , <span class="hljs-number">6</span> , <span class="hljs-number">2</span>],
    <span class="hljs-string">"profit"</span>:[<span class="hljs-number">40</span> , <span class="hljs-number">30</span> ,<span class="hljs-number">6</span>]
}
max_weight = <span class="hljs-number">17</span>
selected_wt = <span class="hljs-number">0</span>
max_profit = <span class="hljs-number">0</span>

<span class="hljs-comment"># finds ratio</span>
ratio = [int(data[<span class="hljs-string">'profit'</span>][i] / data[<span class="hljs-string">'weight'</span>][i]) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(data[<span class="hljs-string">'profit'</span>]))]

<span class="hljs-comment"># sort ratio in descending order, rearranges weight and profit in order of the sorted ratio</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(ratio)):
    <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(i + <span class="hljs-number">1</span> , len(ratio)):
        <span class="hljs-keyword">if</span> ratio[i] &lt; ratio[j]:
            ratio[i] , ratio[j] = ratio[j] , ratio[i]
            data[<span class="hljs-string">'weight'</span>][i] , data[<span class="hljs-string">'weight'</span>][j] = data[<span class="hljs-string">'weight'</span>][j] , data[<span class="hljs-string">'weight'</span>][i]
            data[<span class="hljs-string">'profit'</span>][i] , data[<span class="hljs-string">'profit'</span>][j] = data[<span class="hljs-string">'profit'</span>][j] , data[<span class="hljs-string">'profit'</span>][i]


<span class="hljs-comment"># checks if selected weight with the highest ratio is less than the maximum weight, if so it adds it to knapsack and stores the profit, select the next item.</span>
<span class="hljs-comment"># else the sum of the selected weights is more than max weight, finds fraction</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(ratio)):
    <span class="hljs-keyword">if</span> selected_wt + data[<span class="hljs-string">'weight'</span>][i] &lt;= max_weight:
          selected_wt += data[<span class="hljs-string">'weight'</span>][i]
          max_profit += data[<span class="hljs-string">'profit'</span>][i]
    <span class="hljs-keyword">else</span>:
          frac_wt = (max_weight - selected_wt) / data[<span class="hljs-string">'weight'</span>][i]
          frac_value = data[<span class="hljs-string">'profit'</span>][i] * frac_wt
          max_profit += frac_value
          selected_wt += (max_weight - selected_wt)

print(<span class="hljs-string">f"The maximum profit that can be made from each item is: <span class="hljs-subst">{round(max_profit , <span class="hljs-number">2</span>)}</span> euros"</span>)
<span class="hljs-comment"># Result</span>
<span class="hljs-comment"># The maximum profit that can be made from each item is: 73.0 euros</span>
</code></pre>
<h2 id="heading-applications-of-greedy-algorithms">Applications of Greedy Algorithms</h2>
<p>There are various applications of greedy algorithms. Some of them are:</p>
<ul>
<li><p>[Minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree#:~:text=A%20minimum%20spanning%20tree%20(MST,minimum%20possible%20total%20edge%20weight.) is without any cycles and with the minimum possible total edge weight. This tree is derived from a connected undirected graph with weights.</p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra’s shortest path</a> is a search algorithm that finds the shortest path between a vertex and other vertices in a weighted graph.</p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">Travelling salesman problem</a> involves finding the shortest route that visits different places only once and returns to the starting point</p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Huffman_coding">Huffman coding</a> assigns shorter code to frequently occurring symbols and longer code to less occurring symbols. It is used to encode data efficiently.</p>
</li>
</ul>
<h2 id="heading-advantages-of-using-a-greedy-algorithm">Advantages of Using a Greedy Algorithm</h2>
<p>Greedy algorithms are quite straight forward to implement and easy to understand. They are also very efficient and have a lower complexity time of O(N * logN).</p>
<p>They're useful in solving optimization problems, returning a maximum or minimum value.</p>
<h2 id="heading-disadvantageslimitations-of-using-a-greedy-algorithm">Disadvantages/Limitations of Using a Greedy Algorithm</h2>
<p>Even though greedy algorithms are straightforward and helpful in optimization problems, they don't offer the best solutions at all times.</p>
<p>Also greedy algos only run once, so they don't check the correctness of the result produced.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Greedy algorithms are a straightforward approach to solving optimization problems, returning a minimum or maximum value.</p>
<p>This article explained some examples of greedy algorithms and the approach to tackling each problem. By understanding how a greedy algorithm problems works you can better understand dynamic programming. If you have any questions feel free to reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a>💙.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python lower() – How to Lowercase a Python String with the tolower Function Equivalent ]]>
                </title>
                <description>
                    <![CDATA[ A string is a datatype that consists of characters wrapped in quotation marks. These characters can be letters, symbols, or numbers. In Python, there are different ways of working with strings. These methods are built-in functions that change the res... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-lowercase-python-string/</link>
                <guid isPermaLink="false">66d46150ffe6b1f641b5fa97</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Thu, 03 Nov 2022 16:16:15 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/pexels-pixabay-278881.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A string is a datatype that consists of characters wrapped in quotation marks. These characters can be letters, symbols, or numbers.</p>
<p>In Python, there are different ways of working with strings. These methods are built-in functions that change the results of the string.</p>
<p>For instance, if I want to print out my name with its first letter capitalized, I use the <code>.title()</code> method to capitalize the first letter.</p>
<p>In this article, we will learn how to convert uppercase letters to lowercase letters without using the built-in method.</p>
<h2 id="heading-how-to-convert-a-string-to-lowercase-using-lower">How to Convert a String to Lowercase using <code>.lower()</code></h2>
<p>Strings can consist of different characters – one of those characters being letters of the alphabet. You can write the English alphabet as uppercase or lowercase letters. When changing a string to lowercase, it only applies to the letters.</p>
<p>In Python, there is a built-in method that can change a string that is in uppercase to lowercase. It also applies to strings that have letters both in uppercase and lowercase. The “.lower() “ method changes the strings to lowercase.</p>
<pre><code class="lang-python">name = <span class="hljs-string">"BOB STONE"</span>
print(name.lower()) <span class="hljs-comment"># &gt;&gt; bob stone</span>
name1 = <span class="hljs-string">"Ruby Roundhouse"</span>
print(name1.lower()) <span class="hljs-comment"># &gt;&gt; ruby roundhouse</span>
name2 = <span class="hljs-string">"joHN Wick"</span>
print(name2.lower()) <span class="hljs-comment"># &gt;&gt; john wick</span>
name3 = <span class="hljs-string">"charlieNew"</span>
print(name3.lower()) <span class="hljs-comment"># &gt;&gt; charlienew</span>
</code></pre>
<p>We can see in the above code block that the variables that store each string have uppercase letters. Then with the <code>.lower()</code> method, it converts those letters to lowercase.</p>
<h2 id="heading-other-ways-to-convert-a-python-string-to-lowercase">Other Ways to Convert a Python String to Lowercase</h2>
<p>Apart from the inbuilt method “.lower()”, there are different ways of converting uppercase letters to lowercase letters in Python. In this article, we will look at two different ways.</p>
<p>There are two ways of accessing letters:</p>
<ul>
<li><p>copying them manually into a list or</p>
</li>
<li><p>making use of Unicode standard</p>
</li>
</ul>
<h3 id="heading-how-to-access-letters-from-a-list">How to Access Letters from a List</h3>
<p>The idea is to loop through a list of letters and replace the uppercase letters in a string with lowercase letters.</p>
<p>First, create a variable that stores an input that accepts a string with uppercase letters.</p>
<p>Then, create another variable that stores a list of uppercase letters and lowercase letters.</p>
<p>Last, create the final variable that stores an empty string, which is where the lowercase letters will be stored.</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: ” ))

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

lowercase_letters = ''</span>
</code></pre>
<p>In the list above, we see that it has lowercase letters and uppercase letters. There are 26 letters in the English alphabet, but the index in a list starts from 0, so the count of the alphabet is 51 (for both upper and lowercase letters).</p>
<p>We can also see that the lowercase letters are written first (left side), and the uppercase letters are written second (right side). The indexes of the lowercase letters range from 0 - 25, while the indexes of the upper case letters ranges from 26 - 51.</p>
<p>Next, we loop through each character in the string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
</code></pre>
<p><code>&lt;char&gt;</code> is the new variable name that stores all the characters from the <code>&lt;word&gt;</code> variable.</p>
<p>There are two cases of strings we are going to convert. The first case is the strings with only uppercase letters and the second has strings with special symbols, numerals, some lowercase, and some uppercase letters.</p>
<p><strong>CASE I</strong>: strings with uppercase only</p>
<p>To convert the uppercase letters to lowercase, we have to find the index of each letter stored by the variable <code>&lt;char&gt;</code> from the list. To find an index we use the ".index()" method:</p>
<pre><code class="lang-python">alphabet = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'f'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'h'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'j'</span>, <span class="hljs-string">'k'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'m'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'p'</span>, <span class="hljs-string">'q'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'s'</span>, <span class="hljs-string">'t'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'v'</span>, <span class="hljs-string">'w'</span>, <span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>, <span class="hljs-string">'z'</span>,<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-string">'E'</span>,<span class="hljs-string">'F'</span>,<span class="hljs-string">'G'</span>,<span class="hljs-string">'H'</span>,<span class="hljs-string">'I'</span>,<span class="hljs-string">'J'</span>,<span class="hljs-string">'K'</span>,<span class="hljs-string">'L'</span>,<span class="hljs-string">'M'</span>,<span class="hljs-string">'N'</span>,<span class="hljs-string">'O'</span>,<span class="hljs-string">'P'</span>,<span class="hljs-string">'Q'</span>,<span class="hljs-string">'R'</span>,<span class="hljs-string">'S'</span>,<span class="hljs-string">'T'</span>,<span class="hljs-string">'U'</span>,<span class="hljs-string">'V'</span>,<span class="hljs-string">'W'</span>,<span class="hljs-string">'X'</span>,<span class="hljs-string">'Y'</span>,<span class="hljs-string">'Z'</span>]
word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    print(alphabet.index(char))

<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># Enter a word: GIRL</span>
<span class="hljs-comment"># 32</span>
<span class="hljs-comment"># 34</span>
<span class="hljs-comment"># 43</span>
<span class="hljs-comment"># 37</span>
</code></pre>
<p>In the above code, the indexes of the letters in the "GIRL" are printed.</p>
<p>In the list, the lowercase letters have indexes from 0-25 and uppercase letters have indexes from 26 - 51. When setting the condition ("if" statement) we start checking if the index of the letter is greater than '25' because the first uppercase index starts from '26' .</p>
<p>To get the corresponding lowercase letters, we substract 26 from each uppercase index. When we get the indexes of the lowercase numbers, we use indexing (variable_name[index_number]) to find the corresponding letters. The lowercase letters are now added to the variable name &lt;lower_case_letters&gt; that stores an empty string.</p>
<p>We return the variable &lt;lowercase_letters&gt; by printing it outside the loop.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
      <span class="hljs-keyword">if</span> alphabet.index(char) &gt; <span class="hljs-number">25</span>:
          lowercase_letters += alphabet[alphabet.index(char)<span class="hljs-number">-26</span>]
  print(lowercase_letters)
</code></pre>
<p>This is what the code looks like when we bring it all together:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change_to_lowercase</span>(<span class="hljs-params">word</span>):</span>

  alphabet = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'f'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'h'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'j'</span>, <span class="hljs-string">'k'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'m'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'p'</span>, <span class="hljs-string">'q'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'s'</span>, <span class="hljs-string">'t'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'v'</span>, <span class="hljs-string">'w'</span>, <span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>, <span class="hljs-string">'z'</span>,<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-string">'E'</span>,<span class="hljs-string">'F'</span>,<span class="hljs-string">'G'</span>,<span class="hljs-string">'H'</span>,<span class="hljs-string">'I'</span>,<span class="hljs-string">'J'</span>,<span class="hljs-string">'K'</span>,<span class="hljs-string">'L'</span>,<span class="hljs-string">'M'</span>,<span class="hljs-string">'N'</span>,<span class="hljs-string">'O'</span>,<span class="hljs-string">'P'</span>,<span class="hljs-string">'Q'</span>,<span class="hljs-string">'R'</span>,<span class="hljs-string">'S'</span>,<span class="hljs-string">'T'</span>,<span class="hljs-string">'U'</span>,<span class="hljs-string">'V'</span>,<span class="hljs-string">'W'</span>,<span class="hljs-string">'X'</span>,<span class="hljs-string">'Y'</span>,<span class="hljs-string">'Z'</span>]
  lowercase_letters = <span class="hljs-string">''</span>

  <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
      <span class="hljs-keyword">if</span> alphabet.index(char) &gt; <span class="hljs-number">25</span>:
          lowercase_letters += alphabet[alphabet.index(char)<span class="hljs-number">-26</span>]

  <span class="hljs-keyword">return</span> lowercase_letters

word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
print(change_to_lowercase(word=word))

<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># Enter a word: FERE</span>
<span class="hljs-comment"># fere</span>
<span class="hljs-comment"># Enter a word: PYTHONISFUN</span>
<span class="hljs-comment"># pythonisfun</span>
</code></pre>
<p><strong>CASE II</strong>: strings with special symbols, numerals, lowercase letters alongside uppercase letters.</p>
<p>Before converting the uppercase letters to lowercase, there are some conditions we need to check. The conditions will check if each character <code>&lt;char&gt;</code> from the word:</p>
<ul>
<li><p>is not a letter</p>
</li>
<li><p>has both uppercase and lowercase letters in the word. If some letters in the word are lowercase, they will be left unchanged.</p>
</li>
</ul>
<p>After these checks, it assumes the remaining characters are uppercase letters.</p>
<p>To check if a character is not a letter, we use the “not in” keyword. To check if a character is lowercase, we find the index and compare it to the last count of the lowercase letters in the list.</p>
<p>Again, lowercase letters have indexes from 0-25, and the index of the last lowercase letter is 25. These characters are added to the variable name &lt;lower_case_letters&gt; that stores an empty string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> char <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> alphabet <span class="hljs-keyword">or</span> alphabet.index(char)&lt;=<span class="hljs-number">25</span>:
        lowercase_letters += char
</code></pre>
<p>In the above code block, we used the <code>.index()</code> method to find the position of letters in the alphabet.</p>
<p>For the remaining characters that we assume are uppercase letters, in the list of letters, the indexes of those letters are from 26 - 51. To find their corresponding lowercase letter indexes, we subtract by 26, and use the <code>.index()</code> method to find the letter.</p>
<p>Indexing = variable_name[index_number]. We add the final result to the variable storing the empty string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> char <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> alphabet <span class="hljs-keyword">or</span> alphabet.index(char)&lt;=<span class="hljs-number">25</span>:
        lowercase_letters += char
    <span class="hljs-keyword">else</span>:
        lowercase_letters += alphabet[alphabet.index(char)<span class="hljs-number">-26</span>]
</code></pre>
<p>Then we print lowercase_letters outside the loop:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> char <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> alphabet <span class="hljs-keyword">or</span> alphabet.index(char)&lt;=<span class="hljs-number">25</span>:
        lowercase_letters += char
    <span class="hljs-keyword">else</span>:
        lowercase_letters += alphabet[alphabet.index(char)<span class="hljs-number">-26</span>]
print(lowercase_letters)
</code></pre>
<p>This is what the code looks like when we bring it all together:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change_to_lowercase</span>(<span class="hljs-params">word</span>):</span>

  alphabet = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'f'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'h'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'j'</span>, <span class="hljs-string">'k'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'m'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'p'</span>, <span class="hljs-string">'q'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'s'</span>, <span class="hljs-string">'t'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'v'</span>, <span class="hljs-string">'w'</span>, <span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>, <span class="hljs-string">'z'</span>,<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-string">'E'</span>,<span class="hljs-string">'F'</span>,<span class="hljs-string">'G'</span>,<span class="hljs-string">'H'</span>,<span class="hljs-string">'I'</span>,<span class="hljs-string">'J'</span>,<span class="hljs-string">'K'</span>,<span class="hljs-string">'L'</span>,<span class="hljs-string">'M'</span>,<span class="hljs-string">'N'</span>,<span class="hljs-string">'O'</span>,<span class="hljs-string">'P'</span>,<span class="hljs-string">'Q'</span>,<span class="hljs-string">'R'</span>,<span class="hljs-string">'S'</span>,<span class="hljs-string">'T'</span>,<span class="hljs-string">'U'</span>,<span class="hljs-string">'V'</span>,<span class="hljs-string">'W'</span>,<span class="hljs-string">'X'</span>,<span class="hljs-string">'Y'</span>,<span class="hljs-string">'Z'</span>]
  lowercase_letters = <span class="hljs-string">''</span>

  <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
      <span class="hljs-keyword">if</span> char <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> alphabet <span class="hljs-keyword">or</span> alphabet.index(char)&lt;=<span class="hljs-number">25</span>:
          lowercase_letters += char
      <span class="hljs-keyword">else</span>:
          lowercase_letters += alphabet[alphabet.index(char)<span class="hljs-number">-26</span>]
  <span class="hljs-keyword">return</span> lowercase_letters

word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
print(change_to_lowercase(word=word))

<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># Enter a word: 2022BlackADAM&amp;&amp;</span>
<span class="hljs-comment"># 2022blackadam&amp;&amp;</span>
<span class="hljs-comment"># Enter a word: Weasle2@3568QQQAJHGB</span>
<span class="hljs-comment"># weasle2@3568qqqajhgb</span>
</code></pre>
<h2 id="heading-how-to-access-letters-using-the-unicode-standard">How to Access Letters using the Unicode Standard</h2>
<p>Unicode means universal character encoding standard. According to unicode.org,</p>
<blockquote>
<p>"Unicode standard provides a unique number for every character, no matter what platform, device, application or language."</p>
</blockquote>
<p>In simple terms, all letters from different languages have a unique number representing every character present in Unicode.</p>
<p>We use two methods when working with Unicode in Python: <code>ord()</code> and <code>chr()</code>.</p>
<ul>
<li><p>ord(): this function accepts characters (letters in any language) and returns the unique number under the Unicode standard.</p>
</li>
<li><p>chr(): this function accepts integers and returns the character equivalent under the Unicode standard.</p>
</li>
</ul>
<p>Before diving into the code explanation, here is a chart containing all the unique numbers for the English alphabet, both lowercase and uppercase letters.</p>
<p><img src="https://lh5.googleusercontent.com/BaC12Gudvtl2Wu1uAaFqqNudQKHi0mwoF5H2JT_GtrELW-sPK5IzoybnhL426kPy_4XXas-7MU3PVsmzNQJEJZqoWrq-xhApaoYFZjBuDnA5ugnJFaoBaCb2EcvAVDV5tHJyS2wbi5Wp2Iw8Gka5YWYjVTPVkxbMIwM0Uc86Ude9YNf2FQjxq4xBgQ" alt="Image" width="1063" height="396" loading="lazy"></p>
<p><a target="_blank" href="https://linuxhint.com/understanding-ascii-table/"><em>ASCII Chart representing the unique numbers of english alphabets</em></a></p>
<p>Now that we are familiar with what Unicode is and how to access the values in Python, let’s dive in.</p>
<p>First, create a variable that stores an input that accepts a string with uppercase letters.</p>
<p>Then, create the final variable that stores an empty string, which is where the lowercase letters will be stored.</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: ” ))
lowercase_letters = ''</span>
</code></pre>
<p>Then we loop through each character in the string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
</code></pre>
<p><code>&lt;char&gt;</code> is the new variable name that stores all the characters from the <code>&lt;word&gt;</code> variable.</p>
<p><strong>CASE I</strong>: strings containing uppercase letters only.</p>
<p>Before converting the uppercase letters to lowercase, we need to check if each character from the word is in uppercase.</p>
<p>According to the Unicode chart, the capital letter A has the number “65”, and the capital letter Z has the number “90”. We check if each character <code>&lt;char&gt;</code> in <code>&lt;word&gt;</code> has numbers between 65 and 90. If they do, they are uppercase letters.</p>
<pre><code class="lang-python">print((ord(<span class="hljs-string">'A'</span>)))
<span class="hljs-comment"># RESULT</span>
<span class="hljs-comment"># 65</span>
print((ord(<span class="hljs-string">'Z'</span>)))
<span class="hljs-comment"># RESULT</span>
<span class="hljs-comment"># 90</span>
print((ord(<span class="hljs-string">'F'</span>)))
<span class="hljs-comment"># RESULT</span>
<span class="hljs-comment"># 70</span>
</code></pre>
<p>The <code>ord()</code> function returns the unique number of each letter in uppercase.</p>
<p>To convert uppercase letters to lowercase letters, we add the difference between both cases, “32”, to each number from the uppercase to get the lower case letters.</p>
<p>For example:</p>
<pre><code class="lang-python">number_for_A = ord(<span class="hljs-string">'A'</span>)
number_for_a = ord(<span class="hljs-string">'a'</span>)
difference_a = number_for_a - number_for_A
print(<span class="hljs-string">"Differences in letters"</span> , difference_a)
print(<span class="hljs-string">"The unique number for A"</span>, number_for_A)
print(<span class="hljs-string">"The unique number for a"</span>, number_for_a)

 <span class="hljs-comment"># Results</span>
<span class="hljs-comment"># The unique number for A 65</span>
<span class="hljs-comment"># The unique number for a 97</span>
<span class="hljs-comment"># Differences in letters 32</span>

number_for_F = ord(<span class="hljs-string">'F'</span>)
number_for_f = ord(<span class="hljs-string">'f'</span>)
difference_f = number_for_f - number_for_F
print(<span class="hljs-string">"The unique number for F"</span>, number_for_F)
print(<span class="hljs-string">"The unique number for f"</span>, number_for_f)
print(<span class="hljs-string">"Differences in letters"</span> , difference_f)
<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># The unique number for F 70</span>
<span class="hljs-comment"># The unique number for f 102</span>
<span class="hljs-comment"># Differences in letters 32</span>
</code></pre>
<p>In the above code, ‘a” is 97 on the unicode chart and ‘A’ is 65. The difference between them is 32. If we want to get the value of “a” on the chart, we add 32 to the value of A “65” and get “97”.</p>
<p>So to convert to lowercase, we have to add 32 to each of the numbers of the uppercase letters to get their corresponding lowercase letters.</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
lowercase_letters = <span class="hljs-string">''</span>
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
        char = ord(char) + <span class="hljs-number">32</span>
    print(char)
<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># Enter a word: REAL</span>
<span class="hljs-comment"># 114</span>
<span class="hljs-comment"># 101</span>
<span class="hljs-comment"># 97</span>
<span class="hljs-comment"># 108</span>
</code></pre>
<p>In the above code, we loop through the variable <code>&lt;word&gt;</code> to get access to each character.</p>
<p>Then we check if each character in the variable <code>&lt;word&gt;</code> has a unique number between 65 and 90. If it does, it consists of uppercase letters.</p>
<p>To get the corresponding lowercase letters, we add 32. The result above prints the unique numbers of lowercase letters.</p>
<p>We can match the numbers with their letters by using the <code>chr()</code> function.</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
lowercase_letters = <span class="hljs-string">''</span>
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
        char = ord(char) + <span class="hljs-number">32</span>
        to_letters = chr(char)
    print(to_letters) 


<span class="hljs-comment"># Result</span>
<span class="hljs-comment"># Enter a word: REAL</span>
<span class="hljs-comment"># r</span>
<span class="hljs-comment"># e</span>
<span class="hljs-comment"># a</span>
<span class="hljs-comment"># l</span>
</code></pre>
<p>Now we see that the letters returned are in lowercase. To get the letters in one line, we add it to the variable that stores the empty string and return the variable.</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
lowercase_letters = <span class="hljs-string">''</span>
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
        char = ord(char) + <span class="hljs-number">32</span>
        to_letters = chr(char)
        lowercase_letters += to_letters
print(lowercase_letters)
<span class="hljs-comment"># Result</span>
<span class="hljs-comment"># Enter a word: FERE</span>
<span class="hljs-comment"># fere</span>
</code></pre>
<p>Here's what it looks like when we bring it all together:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change_to_lowercase</span>(<span class="hljs-params">word</span>):</span>
    lowercase_letters = <span class="hljs-string">''</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
        <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
            char = ord(char)+<span class="hljs-number">32</span>
            to_letters = chr(char)
            lowercase_letters += to_letters
    <span class="hljs-keyword">return</span> lowercase_letters
word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
print(change_to_lowercase(word=word))

<span class="hljs-comment"># Results</span>
<span class="hljs-comment"># Enter a word: HARDWORKPAYS</span>
<span class="hljs-comment"># hardworkpays</span>
<span class="hljs-comment"># Enter a word: PYTHONISFUN</span>
<span class="hljs-comment"># pythonisfun</span>
</code></pre>
<p><strong>CASE II:</strong> strings with special symbols, numerals, lowercase alongside uppercase letters.</p>
<p>For strings that have non-letters and some lowercase letters, we add an 'else' statement to return the values as they appear in the string. The uppercase letters are then converted to lowercase:</p>
<pre><code class="lang-python">word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
lowercase_letters = <span class="hljs-string">''</span>
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
    <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
        char = ord(char)+<span class="hljs-number">32</span>
        to_letters = chr(char)
        lowercase_letters += to_letters
    <span class="hljs-keyword">else</span>:
        lowercase_letters += char
print(lowercase_letters)

<span class="hljs-comment"># Result</span>
<span class="hljs-comment"># Enter a word: @#&amp;YEAERS09=</span>
<span class="hljs-comment"># @#&amp;yeaers09=</span>
</code></pre>
<p>Here's what it looks like when we bring it all together:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change_to_lowercase</span>(<span class="hljs-params">word</span>):</span>
    lowercase_letters = <span class="hljs-string">''</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> word:
        <span class="hljs-keyword">if</span> ord(char) &gt;= <span class="hljs-number">65</span> <span class="hljs-keyword">and</span> ord(char) &lt;= <span class="hljs-number">90</span>:
            char = ord(char)+<span class="hljs-number">32</span>
            to_letters = chr(char)
            lowercase_letters += to_letters
        <span class="hljs-keyword">else</span>:
            lowercase_letters += char
    <span class="hljs-keyword">return</span> lowercase_letters
word = str(input(<span class="hljs-string">"Enter a word: "</span> ))
print(change_to_lowercase(word=word))

<span class="hljs-comment"># Enter a word: YOUGOT#$^</span>
<span class="hljs-comment"># yougot#$</span>
<span class="hljs-comment"># Enter a word: BuLLettrAIn@2022</span>
<span class="hljs-comment"># bullettrain@2022</span>
</code></pre>
<p>I know the second method is a lot take in but it also gets you the result, just as the first method does.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, you've learnt about how to convert characters and strings from one case to another. We also took a look at the ASCII table.</p>
<p>The second method is more efficient and straightforward once you know how to use the two important functions. The indexes of the letters are built-in in Python, so there's no need to memorize them.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search in Python – How to Code the Algorithm with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In our daily lives, we're constantly searching for information or trying to find solutions to problems we encounter. When going through search results on the web, we pick the most relevant articles or resources that we think will help us. Search is s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-in-python-with-examples/</link>
                <guid isPermaLink="false">66d4614a55db48792eed3f9d</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Mon, 18 Jul 2022 16:53:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/pexels-pixabay-277593.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In our daily lives, we're constantly searching for information or trying to find solutions to problems we encounter.</p>
<p>When going through search results on the web, we pick the most relevant articles or resources that we think will help us.</p>
<p>Search is such a part of our lives because we cannot always have the answers. And there are various algorithms that help programs run more efficiently and deal with data more effectively.</p>
<h2 id="heading-what-well-cover-in-this-tutorial">What We'll Cover in This Tutorial</h2>
<ul>
<li><p>What is a Search Algorithm?</p>
</li>
<li><p>What is a Binary Search algorithm?</p>
</li>
<li><p>How Binary Search Works – Divide and Conquer</p>
</li>
<li><p>Processes involved in Binary Search Algorithms</p>
</li>
<li><p>Methods Used in Binary Search Algorithms</p>
</li>
<li><p>Real-life examples of Binary Search</p>
</li>
</ul>
<h2 id="heading-what-is-a-search-algorithm">What is a Search Algorithm?</h2>
<p>A search algorithm works to retrieve items from any data structure. It compares the data that comes in as input to the information stored in its database and brings out the result. An example is finding your best friend’s number in your contact list of 1,000 numbers.</p>
<p>There are different types of search algorithms. Some of them are:</p>
<h3 id="heading-linear-search-algorithms">Linear search algorithms</h3>
<p>Linear search algorithms are the simplest of all the search algorithms. As the name implies, they operate in a sequence.</p>
<p>Linear search checks elements in a list one after the other to find a particular key value. This key value is among other items in the list and the algorithm returns the position by going through the check.</p>
<h3 id="heading-dijkstras-algorithm">Dijkstra's algorithm</h3>
<p>Dijkstra's shortest path algorithm is used in more advanced searches. Dijkstra’s algorithm maps out the shortest distance between two nodes. These nodes are often route networks.</p>
<p>This type of search is useful when you're trying to find routes on maps. It gives you options based on finding the shortest path possible.</p>
<h3 id="heading-binary-search-algorithm">Binary Search Algorithm</h3>
<p>Binary search algorithms are also known as half interval search. They return the position of a target value in a sorted list.</p>
<p>These algorithms use the “divide and conquer” technique to find the value's position.</p>
<p>Binary search algorithms and linear search algorithms are examples of simple search algorithms.</p>
<p>In binary search, the middle element in the list is found before comparing with the key value you are searching for. But in linear search, the elements are taken one by one in the list by looping through and comparing with the key value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/differences-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>‌During Binary search, the list is split into two parts to get the middle element: there is the left side, the middle element, and the right side.</p>
<p>The left side contains values smaller than the middle element and the right side contains values that are greater than the middle element. This method uses a sorted list to work.</p>
<p>A sorted list has its items arranged in a particular order. To make search efficient for binary search, the values in the list have to be arranged in the right order to satisfy the process of search. If a list has its values mixed up, it has to be sorted by a sorting algorithm before you perform the search.</p>
<h3 id="heading-sorting-algorithms">Sorting algorithms</h3>
<p>Sorting algorithms accept an unsorted list as an input and return a list with the elements arranged in a particular order (mostly ascending order).</p>
<p>There are <a target="_blank" href="https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c/">different types of sorting algorithms</a>, like insertion sort, quick sort, bubble sort, and merge sort.</p>
<h2 id="heading-how-binary-search-works-divide-and-conquer">How Binary Search Works – Divide and Conquer</h2>
<p>A binary search algorithm uses a technique called “divide and conquer” to tackle its task. The merge sort algorithm employs the same technique to sort items in a list.</p>
<p>In binary search algorithms, the “divide and conquer” method works this way:</p>
<ul>
<li><p>The algorithm splits the list into two parts: the left side and right side, separated by the middle element</p>
</li>
<li><p>It creates a variable to store the value of the item to be searched for</p>
</li>
<li><p>It picks out the middle element and compares it with the item to be searched</p>
</li>
<li><p>If the items compared are equal, then process ends</p>
</li>
<li><p>If not, the middle element is either greater or lesser than the item you're searching for. If the middle element is greater, the algorithm splits the list and searches for the element on the left side. If the middle element is smaller, it splits the list and searches for the element on the right side of the list.</p>
</li>
</ul>
<p>You can implement this method using recursion or iteration in the binary search process.</p>
<h3 id="heading-how-the-binary-search-algorithm-works-step-by-step">How the Binary Search Algorithm Works – Step by Step</h3>
<p>First, before performing the search, you need to sort the list.</p>
<p>Then you create a variable that stores the value to be searched for.</p>
<p>Next, the list is divided into two parts. We sum up the first and last indexes to find the index of the middle element in the list.</p>
<p>When the calculated value of the middle element index is a float (like 3.45), we take the whole part as the index.</p>
<p>Then we compare the value we're searching for and the middle element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/process1--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-binary-search-use-case">Binary Search Use Case</h3>
<h4 id="heading-condition-1">Condition 1</h4>
<p>If the middle element is equal to the value to be searched, the position where the value is will be returned and the process is terminated.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> middle element == to_search 
    <span class="hljs-keyword">return</span> position of middle element 
*code ends*
</code></pre>
<h4 id="heading-using-the-image-above-as-an-example">Using the Image above as an example:</h4>
<p>The middle element = 23, the target value/to_search = 23. Comparing the two values, we see that they are equal on both sides. 23 appears at index 2 in the list. That is the output of the code and the process ends.</p>
<h4 id="heading-condition-2">Condition 2</h4>
<p>If the middle element is not equal to "to_search", then we check the following scenarios:</p>
<p><strong>Scenario 1</strong>: if the middle element is greater than the value to be searched:</p>
<p><code>if middle element &gt; to_search</code></p>
<ul>
<li><p>the search moves to the left side because the values are less than the middle element</p>
</li>
<li><p>the position of the middle element shifts to the left by 1</p>
</li>
<li><p>new_position = index(middle element) - 1</p>
</li>
<li><p>a new search begins and the search ends at that new position and it takes all the values before it.</p>
</li>
</ul>
<h4 id="heading-using-the-image-above-as-an-example-1">Using the image above as an example:</h4>
<pre><code class="lang-python">middle element = <span class="hljs-number">23</span>
to_search = <span class="hljs-number">4</span>
<span class="hljs-keyword">if</span> <span class="hljs-number">23</span> &gt; <span class="hljs-number">4</span>
</code></pre>
<ul>
<li><p>we move to the left side because all numbers less than 23 are stored there. index (23) = 2</p>
</li>
<li><p>new_position = index(23) - 1 = 2-1 = 1</p>
</li>
<li><p>The search will end at index 1 and take all other value(s) before index 1</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/leftside.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Comparing the new middle element (4) to the target value (4), we see they are equal. So the search is terminated and the output is the position "4" occupies in the list (which is index 0).</p>
<p><strong>Scenario 2</strong>: if the middle element is less than the value to be searched:</p>
<p><code>if middle element &lt; to_search</code></p>
<ul>
<li><p>the search moves to the right side because the values are greater than the middle element</p>
</li>
<li><p>the position of the middle element shifts to the right by 1</p>
</li>
<li><p>new_position = index(middle element) + 1</p>
</li>
<li><p>a new search begins at the new position and ends at the last index in the list</p>
</li>
<li><p>all values are taken from the new position to the end of the list</p>
</li>
</ul>
<h4 id="heading-using-the-first-image-as-an-example">Using the first Image as an example:</h4>
<pre><code class="lang-python">middle element = <span class="hljs-number">23</span> 
to_search = <span class="hljs-number">32</span> 
<span class="hljs-keyword">if</span> <span class="hljs-number">23</span> &gt; <span class="hljs-number">32</span>
</code></pre>
<ul>
<li><p>we move to the right side because all numbers greater than 23 are stored there. index(23) = 2 ,</p>
</li>
<li><p>new_position = index(23) + 1 = 2+1 = 3</p>
</li>
<li><p>The search will begin at index 3 and take all other value(s) after index 3</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/rightside.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Comparing the middle element (32) to the target value (32), we see they are equal. So the search is terminated and the output is the position "4" occupies in the list (index 4).</p>
<h2 id="heading-methods-used-in-binary-search-algorithms">‌‌Methods Used in Binary Search Algorithms</h2>
<p>There are two methods that can implement the “divide and conquer” technique in the search. They are iteration and recursion.</p>
<h3 id="heading-what-is-iteration">What is Iteration?</h3>
<p>In order to get elements from a tuple, list, or dictionary, you iterate through the items with loops.</p>
<p>Iteration is a repeated sequence of statements during execution and it has a countable number of values. For example, when looping through random lists, we loop through the actual variable containing the lists to get the values.</p>
<h4 id="heading-code-implementation-for-binary-search-with-iteration">Code implementation for binary search with iteration</h4>
<p>Here's the code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_search</span>(<span class="hljs-params">list_num , to_search</span>):</span>
    first_index = <span class="hljs-number">0</span>
    size = len(list_num)
    last_index = size - <span class="hljs-number">1</span>
    mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
    <span class="hljs-comment"># print(mid_index)</span>
    mid_element = list_num[mid_index]
    <span class="hljs-comment"># print(mid_element)</span>

    is_found = <span class="hljs-literal">True</span>
    <span class="hljs-keyword">while</span> is_found:
        <span class="hljs-keyword">if</span> first_index == last_index:
            <span class="hljs-keyword">if</span> mid_element != to_search:
                is_found = <span class="hljs-literal">False</span>
                <span class="hljs-keyword">return</span> <span class="hljs-string">" Does not appear in the list"</span>

        <span class="hljs-keyword">elif</span> mid_element == to_search:
            <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &gt; to_search:
            new_position = mid_index - <span class="hljs-number">1</span>
            last_index = new_position
            mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
            mid_element = list_num[mid_index]
            <span class="hljs-keyword">if</span> mid_element == to_search:
                <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &lt; to_search:
            new_position = mid_index + <span class="hljs-number">1</span>
            first_index = new_position
            last_index = size - <span class="hljs-number">1</span>
            mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
            mid_element = list_num[mid_index]
            <span class="hljs-keyword">if</span> mid_element == to_search:
                <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>



list_container = [<span class="hljs-number">16</span> , <span class="hljs-number">18</span> , <span class="hljs-number">20</span> , <span class="hljs-number">50</span> , <span class="hljs-number">60</span> , <span class="hljs-number">81</span> , <span class="hljs-number">84</span> , <span class="hljs-number">89</span>]
print(binary_search(list_container , <span class="hljs-number">81</span>))
print(binary_search(list_container , <span class="hljs-number">10</span>))
</code></pre>
<p>Now let's see what's going on here:</p>
<ul>
<li><p>First, we pass in a list and a value to be searched (to_search) as an input to a function.</p>
</li>
<li><p>In the function, we create a variable name of first index and assign it to "0". The first index in a list is always "0".</p>
</li>
<li><p>Then we create four variable names: "size" to store the length of the list, "last_index" to store the index of the last element, "mid_index" to store the operation of finding the middle element index, and "mid_element" to store the middle element gotten from the list using the mid index as position.</p>
</li>
<li><p>Afterwards, we introduce a while loop to make the conditions run on repeat. Above the while loop we create a variable name "is_found" and set it to "True". This condition checks if the "item to be searched" is found or not.</p>
</li>
<li><p>In the while loop, we check all the conditions. The first condition is to check if the middle element and the variable "to_search" are equal. If they are equal, the position of the item will be returned.</p>
</li>
<li><p>Then we check for the second condition (if middle element != item to be searched) which leads us to the two scenarios:<br>  – if the middle element is greater than the item to be searched, the new position will shift to the left once. The search will begin from the first index and end at the new position which is the new last index.<br>  – If the middle element is less than the item to be searched, the new position will shift to the right once. The search will begin from the new position as the new first index and end at the last index.</p>
</li>
</ul>
<p>At the end of these scenarios, we check if the new middle element is the same as the item to be searched. If it is the same, the position of the item will be returned. If not, the conditions are checked until the values are equal.</p>
<p>For error handling, let's say we want to search for a value that does not appear in the list. If we end at the two conditions, the loop will keep running and may eventually crash the system.</p>
<p>To catch the error, we set a condition to check if the first index equals the last index. Then we check if the middle element is equal to the item to be searched. If it is not equal," is found" will be "False". When you run this, it shows an empty array. In my code, the output is a statement.</p>
<p>The final step is to call the function and the result is displayed.</p>
<p><strong>And here are the results:</strong></p>
<p>If the element is in the list, the output is the position.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-194.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the element is not in the list, the output is a statement like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-195.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-what-is-recursion">What is ‌‌Recursion?</h3>
<p>A function is said to be recursive if it makes reference to itself or previous term(s) to solve a task.</p>
<p>A recursive function is repetitive and it is executed in sequence. It starts from a complex problem and breaks things down into a simpler form.</p>
<h4 id="heading-code-implementation-for-binary-search-with-recursion">Code implementation for binary search with recursion</h4>
<p>With recursion, it is a bit simpler and requires less code. Here's what it looks like:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_search</span>(<span class="hljs-params">list_num, first_index, last_index, to_search</span>):</span>
    <span class="hljs-keyword">if</span> last_index &gt;= first_index:

        mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
        mid_element = list_num[mid_index]


        <span class="hljs-keyword">if</span> mid_element == to_search:
            <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &gt; to_search:
            new_position = mid_index - <span class="hljs-number">1</span>
            <span class="hljs-comment"># new last index is the new position</span>
            <span class="hljs-keyword">return</span> binary_search(list_num, first_index, new_position, to_search)

        <span class="hljs-keyword">elif</span> mid_element &lt; to_search:
            new_position = mid_index + <span class="hljs-number">1</span>
             <span class="hljs-comment"># new first index is the new position</span>
            <span class="hljs-keyword">return</span> binary_search(list_num, new_position, last_index, to_search)

    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">" Does not appear in the list"</span>

list_container = [ <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">21</span>, <span class="hljs-number">34</span>, <span class="hljs-number">54</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span> ]
search = <span class="hljs-number">34</span>
first = <span class="hljs-number">0</span>
last= len(list_container) - <span class="hljs-number">1</span>

print(binary_search(list_container,first,last,search))
</code></pre>
<ul>
<li><p>First, a function accepts four inputs: the first index, last index, list, and to_search (item to be searched).</p>
</li>
<li><p>Then we check if the value of the last index is greater than or equal to the value of the first index. If the condition is true, we assign the operation of finding the middle element index to the variable name "mid_index". Then the middle element is gotten from the list using the mid index as position.</p>
</li>
<li><p>We create an "if" statement under the first "if" block to check if the middle element and the variable "to_search" are equal. If they are equal, the position of the item will be returned.</p>
</li>
<li><p>Then we check for the second condition, (if middle element != item to be searched) which leads us to two scenarios:<br>  – if the middle element is greater than the item to be searched, the new position will shift to the left once. The search will begin from the first index and end at the new position. We return the function and pass in the new position as the last index value.<br>  – if the middle element is less than the item to be searched, the new position will shift to the right once. The search will begin from the new position and end at the last index. We return the function and pass in the new position as the first index value.</p>
</li>
<li><p>The last condition will be on the same indent as the first "if" statement. If the to_search is not in the list, it will return a statement</p>
</li>
</ul>
<p>The final step is to call the function and the result is displayed.</p>
<p><strong>And here are the results:</strong></p>
<p>If the element is in the list, the output is the position:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-196.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the element is not in the list, the output is a statement:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-197.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-real-life-examples-of-binary-search">Real-life Examples of Binary Search‌</h2>
<p>You might not realize it, but we perform binary search all the time. Here are a few examples of how you might use or encounter it in your daily life or work:</p>
<ul>
<li><p>Searching for a word in a dictionary</p>
</li>
<li><p>searching for a literature text book in a literature section in a library</p>
</li>
<li><p>searching for an element in a sorted list</p>
</li>
<li><p>searching for students taller than 5 feet 3 inches in a line of students arranged according to their heights.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>At the end of this article, you should be familiar with how binary search algorithms work and how to implement them in code.</p>
<p>It's fine if you could not grasp everything at once – just give yourself some time and practice. If you encounter any errors or have questions, you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a>.</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Wordle Clone with Python ]]>
                </title>
                <description>
                    <![CDATA[ Solving puzzles is a way to relax and pass the time after a long day. It is also beneficial to the mind. And even better – there are correlations between puzzle-solving and increased problem-solving skills. Wordle is a new word puzzle game that chall... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/building-a-wordle-game/</link>
                <guid isPermaLink="false">66d4614c230dff016690587d</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Thu, 12 May 2022 21:24:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/pexels-suzy-hazelwood-1822568.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Solving puzzles is a way to relax and pass the time after a long day. It is also beneficial to the mind.</p>
<p>And even better – there are correlations between puzzle-solving and increased problem-solving skills.</p>
<p><a target="_blank" href="https://wordlegame.org/">Wordle</a> is a new word puzzle game that challenges its players to guess a five-letter word in six tries.</p>
<p>In this tutorial, you will build a Wordle-like guessing game with the same rules as the original game. We'll build the game in Python. Working through this challenge will improve your knowledge of functions and while loops, and it will help you become more familiar with the zip method.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Basic knowledge of Python</li>
</ul>
<h2 id="heading-what-well-cover">What We'll Cover:</h2>
<ul>
<li><p>How the game works</p>
</li>
<li><p>How to write the game logic</p>
</li>
<li><p>Results of the game</p>
</li>
</ul>
<h2 id="heading-how-the-game-works">How the Game Works</h2>
<p>The game will consist of:</p>
<ul>
<li><p>a variable that stores a five-letter word called "hidden_word".</p>
</li>
<li><p>input from a user.</p>
</li>
<li><p>a variable that stores the number of times (up to 6 tries) the user tries to guess the word.</p>
</li>
<li><p>a condition to check if a letter is guessed correctly and in the right position, indicated by "✔"</p>
</li>
<li><p>another condition to check if a letter is guessed correctly but in the wrong position, indicated by "➕"</p>
</li>
<li><p>the final condition to check if a letter is guessed but not in the hidden word, indicated by "❌"</p>
</li>
</ul>
<h2 id="heading-how-to-write-the-game-logic">How to Write the Game Logic</h2>
<h3 id="heading-first-function-block">First Function Block</h3>
<p>First, we need to inform players about the rules. This is necessary so people know how to play properly.</p>
<p>Start off by creating a function with the name "game_instruction".</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">game_instruction</span>():</span>
</code></pre>
<p>Then, pass in the instructions as a string to the "print" function to show the result. Wrap the strings in docstrings (""" """) because the symbols ("✔❌❌✔➕") will be wrapped in double quotations (" ") . Also each instruction will appear on a new line without using the ("\n") <a target="_blank" href="https://replit.com/@HeritageAlabi/triplequote#main.py">tag</a>.</p>
<pre><code class="lang-python">print(<span class="hljs-string">"""Wordle is a single player game
A player has to guess a five letter hidden word
You have six attempts
Your Progress Guide "✔❌❌✔➕"
"✔" Indicates that the letter at that position was guessed correctly
"➕" indicates that the letter at that position is in the hidden word, but in a different position
"❌" indicates that the letter at that position is wrong, and isn't in the hidden word   """</span>)
</code></pre>
<p>Each sentence is started on a new line, and it will appear that way on the console. We wrap up by calling our function so the instructions will be printed on the screen.</p>
<pre><code class="lang-python">game_instruction()
</code></pre>
<p>If you get an error, it could either be that you forget to put the colon (:) at the end of the function definition <code>def game_instruction()</code> or your code isn't formatted properly. Pay attention to the console error logged, as it will guide you.</p>
<h3 id="heading-bringing-it-together">Bringing it together</h3>
<pre><code class="lang-python"> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">game_instruction</span>():</span>
     print(<span class="hljs-string">"""Wordle is a single player game
A player has to guess a five letter hidden word
You have six attempts
Your Progress Guide "✔❌❌✔➕"
"✔" Indicates that the letter at that position was guessed correctly
"➕" indicates that the letter at that position is in the hidden word, but in a different position
"❌" indicates that the letter at that position is wrong, and isn't in the hidden word   """</span>)
game_instruction()
</code></pre>
<p>And finally, if you run your code and there is no result on your console, it means that you probably forgot to call the function.</p>
<h3 id="heading-output">Output</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/game_instruction.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Game instructions for players</em></p>
<h3 id="heading-second-function-block">Second Function Block</h3>
<p>The next step is working with the user's entry and comparing it with the hidden word. The ability to do that is essential to the game.</p>
<p>Create a function called "check_word". In the code block, create a variable named "hidden word" and assign it to any five letter word of your choice. This hidden word is what the user will try to guess correctly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
</code></pre>
<p>Since the player has 6 tries, assign a new variable called "attempt" to the value of "6" and create a while statement.</p>
<p>It's best to use a while loop here because the process runs until the user guesses the right word or exhausts their tries. The condition for the while statement to run is if the number of attempts is greater than "0".</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
</code></pre>
<p>The user's input is then created inside the while loop, and conditions are checked against the hidden word. If the user's entry is the same as the hidden word, the loop ends and the game is over.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
</code></pre>
<p>Format strings ( f" ") are another method of joining variables and strings together without using the "+" sign.</p>
<p>Here's an example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Instead of,</span>
print(<span class="hljs-string">"you have"</span> + attempt + <span class="hljs-string">" attempt(s) ,, \n"</span>) <span class="hljs-comment"># '\n' is used for new line</span>

<span class="hljs-comment"># use this,</span>
print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n"</span>) <span class="hljs-comment"># the variable to be printed is wrapped in curly braces</span>
</code></pre>
<p>If the user's entry is not equal to the hidden word, introduce an else statement and all conditions will be checked in the "else" block. The attempt decreases by 1 and the attempts left are printed on the console as the user plays the game.</p>
<pre><code class="lang-python">
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
      attempt = attempt - <span class="hljs-number">1</span>
      print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n "</span>)
</code></pre>
<p>If the user's input does not match the hidden word, there are three conditions to be checked:</p>
<ul>
<li><p>First, if the letter is in the wrong position but in the hidden word, print a "➕" beside the letter.</p>
</li>
<li><p>Second, if the letter is in the right position and in the hidden word, print a "✔" beside the letter.</p>
</li>
<li><p>Third, if the letter is not in the hidden word at all, print an "❌" beside the letter.</p>
</li>
</ul>
<p>To compare the letters both in the user's input and the hidden word, include a for loop alongside a zip() function as a statement.</p>
<p><code>for i, j in zip(food, drink):</code></p>
<p>A zip() function is a built in function that loops through items like lists and tuples. It can extract values from multiple variables of the same size.</p>
<p>For strings, you can't directly use the zip() function alone. The "for" loop is included to get the letters from the variables that store the strings.</p>
<p>Here's an example:</p>
<p>A user enters a five letter word and a variable with a five letter word is created. Looping through the two variables at the same time with zip(), all the elements will be printed and separated by a hyphen.</p>
<p>Code block</p>
<pre><code class="lang-python">user_entry = input(<span class="hljs-string">"spell 5 letter word: "</span>)
default_value = <span class="hljs-string">"shell"</span>
<span class="hljs-keyword">for</span> i, j <span class="hljs-keyword">in</span> zip(user_entry, default_value):
  print(i + <span class="hljs-string">" - "</span> +  j)
</code></pre>
<p>Output</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-82.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Back to our code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
      attempt = attempt - <span class="hljs-number">1</span>
      print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n "</span>)
      <span class="hljs-keyword">for</span> char, word <span class="hljs-keyword">in</span> zip(hidden_word, guess):
            <span class="hljs-keyword">if</span> word <span class="hljs-keyword">in</span> hidden_word <span class="hljs-keyword">and</span> word <span class="hljs-keyword">in</span> char:
                print(word + <span class="hljs-string">" ✔ "</span>)

            <span class="hljs-keyword">elif</span> word <span class="hljs-keyword">in</span> hidden_word:
                print(word + <span class="hljs-string">" ➕ "</span>)
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">" ❌ "</span>)
</code></pre>
<p>Let's go through what's happening here:</p>
<p><code>for char, word in zip(hidden_word, guess)</code> - this statement means looping through <code>hidden_word</code> with variable name <code>char</code> and looping through <code>guess</code> with variable name <code>word</code>. All the letters in the hidden word are accessed by <code>char</code> and all the letters in guess are accessed by <code>word</code>.</p>
<p>Then the three conditions mentioned earlier will be checked comparing both letters in <code>word</code> (the user's input) and <code>char</code> in (hidden word):</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
      attempt = attempt - <span class="hljs-number">1</span>
      print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n "</span>)
      <span class="hljs-keyword">for</span> char, word <span class="hljs-keyword">in</span> zip(hidden_word, guess):
            <span class="hljs-keyword">if</span> word <span class="hljs-keyword">in</span> hidden_word <span class="hljs-keyword">and</span> word <span class="hljs-keyword">in</span> char:
                print(word + <span class="hljs-string">" ✔ "</span>)

            <span class="hljs-keyword">elif</span> word <span class="hljs-keyword">in</span> hidden_word:
                print(word + <span class="hljs-string">" ➕ "</span>)
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">" ❌ "</span>)
      <span class="hljs-keyword">if</span> attempt == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">" Game over !!!! "</span>)
</code></pre>
<p>The final step is to call the function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
      attempt = attempt - <span class="hljs-number">1</span>
      print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n "</span>)
      <span class="hljs-keyword">for</span> char, word <span class="hljs-keyword">in</span> zip(hidden_word, guess):
            <span class="hljs-keyword">if</span> word <span class="hljs-keyword">in</span> hidden_word <span class="hljs-keyword">and</span> word <span class="hljs-keyword">in</span> char:
                print(word + <span class="hljs-string">" ✔ "</span>)

            <span class="hljs-keyword">elif</span> word <span class="hljs-keyword">in</span> hidden_word:
                print(word + <span class="hljs-string">" ➕ "</span>)
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">" ❌ "</span>)
      <span class="hljs-keyword">if</span> attempt == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">" Game over !!!! "</span>)

check_word()
</code></pre>
<p>Bringing all the code blocks together, it should look like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">game_instruction</span>():</span>
    print(<span class="hljs-string">"""Wordle is a single player game 
A player has to guess a five letter hidden word 
You have six attempts 
Your Progress Guide "✔❌❌✔➕"  
"✔" Indicates that the letter at that position was guessed correctly 
"➕" indicates that the letter at that position is in the hidden word, but in a different position 
"❌" indicates that the letter at that position is wrong, and isn't in the hidden word   """</span>)


game_instruction()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_word</span>():</span>
  hidden_word = <span class="hljs-string">"snail"</span>
  attempt = <span class="hljs-number">6</span>
  <span class="hljs-keyword">while</span> attempt &gt; <span class="hljs-number">0</span>:
    guess = str(input(<span class="hljs-string">"Guess the word: "</span>))
    <span class="hljs-keyword">if</span> guess == hidden_word:
      print(<span class="hljs-string">"You guessed the words correctly! WIN 🕺🕺🕺 "</span>)
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
      attempt = attempt - <span class="hljs-number">1</span>
      print(<span class="hljs-string">f"you have <span class="hljs-subst">{attempt}</span> attempt(s) ,, \n "</span>)
      <span class="hljs-keyword">for</span> char, word <span class="hljs-keyword">in</span> zip(hidden_word, guess):
            <span class="hljs-keyword">if</span> word <span class="hljs-keyword">in</span> hidden_word <span class="hljs-keyword">and</span> word <span class="hljs-keyword">in</span> char:
                print(word + <span class="hljs-string">" ✔ "</span>)

            <span class="hljs-keyword">elif</span> word <span class="hljs-keyword">in</span> hidden_word:
                print(word + <span class="hljs-string">" ➕ "</span>)
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">" ❌ "</span>)
      <span class="hljs-keyword">if</span> attempt == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">" Game over !!!! "</span>)

check_word()
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Great job! You are done creating a word puzzle game with Python. The code sample is found <a target="_blank" href="https://replit.com/@HeritageAlabi/woordle-game#main.py">here</a>, and you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a> if you have any questions. 💙</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
