<?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" version="2.0"><channel><title><![CDATA[Scrapped Script]]></title><description><![CDATA[👋 Hi, I’m Sirus

👀 I’m interested in embedded systems software engineering, and AI/ML

🌱 I’m currently a computer sci undergrad at Oregon State University]]></description><link>https://scrappedscript.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1693093280811/vxPSRKb59.png</url><title>Scrapped Script</title><link>https://scrappedscript.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 19 Apr 2026 06:02:09 GMT</lastBuildDate><atom:link href="https://scrappedscript.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a Live Concert Enhancement Platform for TikTok with Next.js]]></title><description><![CDATA[Introduction

I recently participated in the TikTok TechJam hackathon and developed "TikTok Concerts," a platform enhancing live concert experiences on TikTok Live. The project features event scheduling, a global events map, and user interfaces for a...]]></description><link>https://scrappedscript.com/building-a-live-concert-enhancement-platform-for-tiktok-with-nextjs</link><guid isPermaLink="true">https://scrappedscript.com/building-a-live-concert-enhancement-platform-for-tiktok-with-nextjs</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[React]]></category><category><![CDATA[Tiktok]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Wed, 10 Jul 2024 17:18:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720631005567/ad93f162-f245-4f6b-8e08-d197a7235460.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<blockquote>
<p>I recently participated in the TikTok TechJam hackathon and developed "TikTok Concerts," a platform enhancing live concert experiences on TikTok Live. The project features event scheduling, a global events map, and user interfaces for artists and fans, built using Next.js, TypeScript, React, and Tailwind CSS. If you find the project interesting, please explore the platform and consider voting for it in the hackathon!</p>
</blockquote>
<p>I just submitted my project for the <a target="_blank" href="https://tiktoktechjam2024.devpost.com/">TikTok TechJam hackathon</a>!</p>
<p>For those who don't know, TikTok just held its first hackathon. TechJam is a hackathon open to college students, with multiple tracks to choose from. I chose the music discovery track. The goal was to create a project that enhances artist exposure on TikTok, promotes diverse content discovery, boosts the viral potential of music on TikTok, and increases engagement and interaction between artists and fans.</p>
<p>TikTok is a social media platform known for its short videos, and it has become a major player in the music industry. Many artists have gained popularity through viral TikTok videos, making it an important platform for music discovery and promotion.</p>
<h3 id="heading-overview-of-tiktok-concerts">Overview of TikTok Concerts</h3>
<iframe width="560" height="315" src="https://www.youtube.com/embed/V94v3FHUqUc?si=C23glEvyl85kg_xB"></iframe>

<p>My project, titled <a target="_blank" href="https://tiktok-concerts.vercel.app/">TikTok Concerts</a>, is designed to enhance the experience of watching live concerts on TikTok Live. It offers several features to help artists and users connect more easily.</p>
<p>The inspiration for this project came from an event called <a target="_blank" href="https://newsroom.tiktok.com/en-us/tiktok-in-the-mix-breaks-record-for-biggest-ever-live-event-on-tiktok">TikTok In The Mix</a>. This event was the first global live concert and set the record for the biggest live event ever on TikTok. Since it was so popular, I thought it would be a good idea to create features that enhance the live concert experience for both artists and fans. These features will encourage artists to share their performances on TikTok Live and invite fans to watch through the TikTok app. It will also help smaller artists reach a wider audience.</p>
<h3 id="heading-what-it-does">What it Does</h3>
<p>My project supports the following main features:</p>
<ul>
<li><p><strong>Event Scheduling:</strong> Artists can schedule their live performances and make them publicly available.</p>
</li>
<li><p><strong>Global Events Map:</strong> A dynamic map showing all scheduled events worldwide.</p>
</li>
</ul>
<p>Fans can go to <code>/users</code> to see upcoming events on a dynamic map and view details like the date and description of each event. Artists can go to <code>/artists</code> to see events they have scheduled, delete events, update events, and add new events. The website is also designed to be responsive on smaller screens.</p>
<p>For example, an artist can schedule a live performance, and fans can easily find and join the event through the global events map. This makes it easier for artists to promote their events and for fans to discover new music.</p>
<h3 id="heading-how-i-built-it">How I Built it</h3>
<p>This project is built using the following technologies:</p>
<ul>
<li><p><strong>Framework:</strong> <a target="_blank" href="https://nextjs.org/">Next.js</a></p>
</li>
<li><p><strong>Language:</strong> <a target="_blank" href="https://www.typescriptlang.org/">Ty</a><a target="_blank" href="https://www.typescriptlang.org/">peScript</a></p>
</li>
<li><p><strong>UI Library:</strong> <a target="_blank" href="https://reactjs.org/">React</a></p>
</li>
<li><p><strong>Styling:</strong> <a target="_blank" href="https://nextjs.org/">Tail</a><a target="_blank" href="https://tailwindcss.com/">wind</a></p>
</li>
<li><p><strong>Database:</strong> MongoDB</p>
</li>
<li><p><strong>API:</strong> Integration w<a target="_blank" href="https://tailwindcss.com/">i</a>th Google Maps API</p>
</li>
<li><p><strong>Deployment:</strong> Vercel</p>
</li>
</ul>
<p>I used Next.js with React to create the pages, app layout, client components, and server components. I used TypeScript for type safety and to create interfaces. I used MongoDB to design the database event schema and model.</p>
<p>Next.js was chosen for its powerful features like server-side rendering and static site generation, which help improve performance and SEO. TypeScript ensures type safety and reduces runtime errors, while Tailwind CSS provides a utility-first approach to design, ensuring responsive and consistent styling.</p>
<h2 id="heading-background-and-technology-overview">Background and Technology Overview</h2>
<h3 id="heading-introduction-to-nextjs">Introduction to Next.js</h3>
<p>Next.js is a powerful, open-source JavaScript framework built on top of React, created by Vercel (formerly known as ZEIT). It offers a robust set of features for building modern web applications, including server-side rendering (SSR), static site generation (SSG), and automatic code splitting. These capabilities make Next.js an excellent choice for developers looking to create high-performance, SEO-friendly web applications.</p>
<h3 id="heading-key-features-of-nextjs-relevant-to-the-project">Key Features of Next.js Relevant to the Project</h3>
<p>The "TikTok Concerts" project uses several important features of Next.js to build a dynamic, responsive, and high-performance web application. Here’s a detailed look at how these features are used:</p>
<ol>
<li><p>App directory structure and nested routing</p>
<ul>
<li>The <code>app</code> directory provides a more intuitive and nested routing system. For example, routes for artists and users are organized within subdirectories, making the code easier to maintain.</li>
</ul>
</li>
<li><p>Server actions</p>
<ul>
<li><p><strong>Data Fetching</strong>: Instead of traditional API routes, server actions fetch data directly within components, reducing the need for client-side fetching and improving performance.</p>
</li>
<li><p><strong>Data Mutations</strong>: Actions like creating, updating, or deleting events are handled server-side within the component's scope. This streamlines the logic and enhances security.</p>
</li>
</ul>
</li>
<li><p>Server side rendering</p>
<ul>
<li><p>In Next.js you can create server components to render UI on the server</p>
</li>
<li><p>Server components can improve performance by reducing the amount of client-side rendering</p>
</li>
<li><p>Server-side rendering helps with search engine optimization (SEO) because search engines can crawl and index content more effectively when it's rendered on the server.</p>
</li>
</ul>
</li>
<li><p>Next.js router cache</p>
<ul>
<li><p>Next.js Router Cache improves page navigation by storing the results of data fetching for each page.</p>
</li>
<li><p><strong>Faster Navigation</strong>: Pages you have visited before load almost instantly when you revisit them, improving the user experience.</p>
</li>
<li><p><strong>Efficient Data Management</strong>: Reduces unnecessary data fetching, improving overall application performance.</p>
</li>
</ul>
</li>
<li><p>TypeScript Integration</p>
<ul>
<li><p>TypeScript enhances code quality with type safety and clear data structures</p>
</li>
<li><p><strong>Type Safety</strong>: Reduces runtime errors and improves development efficiency.</p>
</li>
<li><p><strong>Interfaces and Types</strong>: Ensures consistency across the codebase.</p>
</li>
</ul>
</li>
<li><p>Tailwind Integration</p>
<ul>
<li><p>Tailwind CSS provides a utility-first approach to design, ensuring responsive and consistent styling across components</p>
</li>
<li><p><strong>Responsive Design</strong>: The design adapts to different devices, ensuring a consistent and user-friendly experience.</p>
</li>
<li><p><strong>Consistent Styling</strong>: Simplifies the styling process using reusable utility classes.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-user-experience-design">User Experience Design</h2>
<h3 id="heading-uiux-principles-for-engagement">UI/UX Principles for Engagement</h3>
<ol>
<li><p><strong>Responsive Design</strong>: Ensures the website is accessible and user-friendly on different devices, enhancing the overall user experience.</p>
</li>
<li><p><strong>User and Artist Pages</strong>: Separate pages for users and artists to manage and view events, offering a customized experience for each type of user.</p>
</li>
<li><p><strong>Interactive Features</strong>: Includes elements like event details and descriptions to engage users and provide them with relevant information.</p>
</li>
</ol>
<p><a target="_blank" href="https://tiktok-concerts.vercel.app/users"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720630334255/9b1ebd55-1b08-4b22-9a4b-f14958fb95e5.png" alt="Screenshot of a website titled &quot;TikTok Concerts,&quot; showing upcoming events on a map of the United States, focusing on California with event locations marked in San Francisco, Los Angeles, and San Diego. Below the map is a description of a &quot;Jazz Night&quot; event scheduled on 2024-08-15. The website has navigation links for Home, About, Users, Artists, and GitHub Repo at the top." class="image--center mx-auto" /></a></p>
<h2 id="heading-development-process">Development Process</h2>
<p>Feel free to follow along with my code by visiting the <a target="_blank" href="https://github.com/sirus-the-beaver/tiktok-concerts">GitHub repo</a>.</p>
<h3 id="heading-setting-up-the-development-environment-with-nextjs">Setting Up the Development Environment with Next.js</h3>
<p>I started by setting up a new Next.js project with TypeScript support:</p>
<pre><code class="lang-bash">npx create-next-app@latest
</code></pre>
<p>From there, I answered the prompts in the terminal as follows:</p>
<ol>
<li><p><strong>What is your project named?</strong> tiktok-concerts</p>
</li>
<li><p><strong>Would you like to use TypeScript?</strong> Yes</p>
</li>
<li><p><strong>Would you like to use ESLint?</strong> Yes</p>
</li>
<li><p><strong>Would you like to use Tailwind CSS?</strong> Yes</p>
</li>
<li><p>Would you like to use <code>src/</code> directory? Yes</p>
</li>
<li><p><strong>Would you like to use App Router? (recommended)</strong> Yes</p>
</li>
<li><p><strong>Would you like to customize the default import alias (@/*)?</strong> No</p>
</li>
</ol>
<p>After answering these prompts, your project will be configured as specified, and all the dependencies will be automatically installed.</p>
<h3 id="heading-building-the-page-routes">Building the page routes</h3>
<p>Within my <code>src</code> directory, I created a new folder called <code>app</code> to store all the page routes. The <code>app</code> folder contains the following items:</p>
<ul>
<li>A CSS file that imports Tailwind, where you can also define custom CSS rules.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-keyword">@tailwind</span> base;
<span class="hljs-keyword">@tailwind</span> components;
<span class="hljs-keyword">@tailwind</span> utilities;

<span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--foreground-rgb</span>: <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>;
  <span class="hljs-attribute">--background-start-rgb</span>: <span class="hljs-number">214</span>, <span class="hljs-number">219</span>, <span class="hljs-number">220</span>;
  <span class="hljs-attribute">--background-end-rgb</span>: <span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>;
}

<span class="hljs-keyword">@media</span> (<span class="hljs-attribute">prefers-color-scheme:</span> dark) {
  <span class="hljs-selector-pseudo">:root</span> {
    <span class="hljs-attribute">--foreground-rgb</span>: <span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>;
    <span class="hljs-attribute">--background-start-rgb</span>: <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>;
    <span class="hljs-attribute">--background-end-rgb</span>: <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>;
  }
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(var(--foreground-rgb));
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">linear-gradient</span>(
      to bottom,
      transparent,
      rgb(var(--background-end-rgb))
    )
    <span class="hljs-built_in">rgb</span>(var(--background-start-rgb));
}

<span class="hljs-keyword">@layer</span> utilities {
  <span class="hljs-selector-class">.text-balance</span> {
    <span class="hljs-attribute">text-wrap</span>: balance;
  }
}
</code></pre>
<ul>
<li><p>A home page</p>
<pre><code class="lang-typescript">  <span class="hljs-string">"use client"</span>;
  <span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

  <span class="hljs-comment">/**
   * Home page component
   * 
   * @returns The home page component.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
      &lt;main className=<span class="hljs-string">"flex flex-col items-center gap-10 justify-between p-4 sm:p-8 md:p-16 lg:p-24"</span>&gt;
        &lt;h1 className=<span class="hljs-string">"text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-bold my-4"</span>&gt;Welcome to TikTok Concerts!&lt;/h1&gt;
        &lt;p className=<span class="hljs-string">"text-sm sm:text-base md:text-lg lg:text-xl"</span>&gt;Discover live streamed concerts and performances near you.&lt;/p&gt;
      &lt;/main&gt;
    );
  }
</code></pre>
</li>
<li><p>An app layout that imports the CSS file, defines metadata for the homepage, and contains the content inherited throughout the rest of the app.</p>
</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-keyword">type</span> { Metadata } <span class="hljs-keyword">from</span> <span class="hljs-string">"next"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./globals.css"</span>;
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> ToggleMenu <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/ToggleMenu"</span>;

<span class="hljs-comment">// Metadata for the layout.</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> metadata: Metadata = {
  title: <span class="hljs-string">"TikTok Concerts"</span>,
  description: <span class="hljs-string">"Watch your favorite artists perform live on TikTok."</span>
};

<span class="hljs-comment">/**
 * Root layout component.
 * 
 * @param children - The content to be rendered within the layout.
 * 
 * @returns The layout component.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RootLayout</span>(<span class="hljs-params">{
  children,
  }: Readonly&lt;{
    children: React.ReactNode;
  }&gt;</span>) </span>{
    <span class="hljs-keyword">return</span> (
      &lt;html lang=<span class="hljs-string">"en"</span>&gt;
      &lt;body&gt;
        &lt;div className=<span class="hljs-string">"flex flex-col h-screen justify-between"</span>&gt;
          &lt;ToggleMenu /&gt;

          &lt;main className=<span class="hljs-string">"mb-auto p-4 h-fit"</span>&gt;
            {children}
          &lt;/main&gt;

          &lt;footer className=<span class="hljs-string">"h-10 text-center"</span>&gt;
            &lt;p&gt;
            Disclaimer: This project, TikTok Concerts, is not officially affiliated <span class="hljs-keyword">with</span>, endorsed by, or sponsored by TikTok. All trademarks and copyrights are the property <span class="hljs-keyword">of</span> their respective owners.
            &lt;/p&gt;
            &lt;p&gt;&amp;copy; <span class="hljs-number">2024</span> Sirus Salari. All rights reserved&lt;/p&gt;
          &lt;/footer&gt;
        &lt;/div&gt;
      &lt;/body&gt;
      &lt;/html&gt;
    );
}
</code></pre>
<ul>
<li><p>A separate folder for each page, including <code>/about</code>, <code>/artists</code>, <code>/update</code>, and <code>/users</code></p>
<ul>
<li><p>Within each folder, there is a <code>page.tsx</code> file where you write out the HTML for the page, and import components</p>
</li>
<li><p>Additionally, within each folder, there is a <code>layout.tsx</code> file where you define metadata for that page and inherit the root app layout.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-creating-the-components">Creating the components</h3>
<p>Within the <code>src</code> directory, there's a folder called <code>components</code>. Inside the components directory, I created the following components:</p>
<ul>
<li><p>EventCard - A server component that effectively fetches, displays, and provides options to delete or update events in a user-friendly manner</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { deleteEvent, getEvents } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/action"</span>;

  <span class="hljs-comment">/**
   * Get all events.
   * 
   * @returns All events.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetEvents</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">try</span> {
          <span class="hljs-keyword">const</span> events = <span class="hljs-keyword">await</span> getEvents();
          <span class="hljs-keyword">if</span> (events.length === <span class="hljs-number">0</span>) {
              <span class="hljs-keyword">return</span> &lt;h1&gt;No Events&lt;/h1&gt;;
          } <span class="hljs-keyword">else</span> {
              <span class="hljs-keyword">return</span> (
                  &lt;div className=<span class="hljs-string">'grid grid-rows-1 md:grid-rows-2 lg:grid-rows-3 gap-5'</span>&gt;
                      {events.map(<span class="hljs-function">(<span class="hljs-params">event: <span class="hljs-built_in">any</span></span>) =&gt;</span> (
                          &lt;div key={event._id} className=<span class="hljs-string">'p-5 border rounded shadow-md'</span>&gt;
                              &lt;h3 className=<span class="hljs-string">'text-center text-lg md:text-xl lg:text-2xl font-bold'</span>&gt;{event.title <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/h3&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;Description: &lt;<span class="hljs-regexp">/b&gt;{event.description as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;<span class="hljs-built_in">Date</span>: &lt;<span class="hljs-regexp">/b&gt;{event.date as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;Address: &lt;<span class="hljs-regexp">/b&gt;{event.address as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.city <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.state <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.zip <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                              &lt;form action={deleteEvent} className=<span class="hljs-string">'m-4'</span>&gt;
                                  &lt;input hidden <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"id"</span> defaultValue={event._id.toString()}/&gt;
                                  &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span> className=<span class="hljs-string">'hover:bg-gradient-to-r from-splash to-razzmatazz hover:text-black inline-flex justify-center py-2 px-4 sm:px-6 md:px-8 lg:px-10 border border-transparent shadow-sm text-sm sm:text-base md:text-lg lg:text-xl font-medium rounded-md text-white'</span>&gt;Delete&lt;/button&gt;
                              &lt;/form&gt;
                              &lt;form action=<span class="hljs-string">"/update"</span> className=<span class="hljs-string">'m-4'</span>&gt;
                                  &lt;input hidden <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"id"</span> defaultValue={event._id.toString()}/&gt;
                                  &lt;button className=<span class="hljs-string">'hover:bg-gradient-to-r from-splash to-razzmatazz hover:text-black inline-flex justify-center py-2 px-4 sm:px-6 md:px-8 lg:px-10 border border-transparent shadow-sm text-sm sm:text-base md:text-lg lg:text-xl font-medium rounded-md text-white'</span>&gt;Update&lt;/button&gt;
                              &lt;/form&gt;
                          &lt;/div&gt;
                      ))}
                  &lt;/div&gt;
              );
          }
      } <span class="hljs-keyword">catch</span> (error) {
          <span class="hljs-built_in">console</span>.log(error);
      }
  };
</code></pre>
<ul>
<li><p>This component is used in the <code>/artists</code> page, and imports the server actions for deleting and fetching events</p>
</li>
<li><p>First, a call is made to the getEvents server action. If no data is returned, the component will display HTML stating that there are no events.</p>
</li>
<li><p>If data is returned, each event in the array is mapped to a <code>div</code> with the key attribute set to the MongoDB ObjectID value of the event.</p>
</li>
<li><p>Within the <code>div</code>, there are child elements to display the event's details, such as the title, description, date, address, city, state, and zip code.</p>
</li>
<li><p>Additionally, each <code>div</code> contains two forms: a delete form that submits to the deleteEvent server action with the event's ObjectID as a hidden input, and an update form that redirects to /update with the event's ObjectID as a hidden input.</p>
</li>
<li><p>Events are displayed in a responsive grid layout that adjusts the number of rows based on the screen size.</p>
</li>
</ul>
</li>
<li><p>EventForm - A client component that provides a user-friendly interface for creating and submitting new events, with responsive design and consistent styling</p>
<pre><code class="lang-typescript">  <span class="hljs-string">"use client"</span>;
  <span class="hljs-keyword">import</span> { createEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/action"</span>;
  <span class="hljs-keyword">import</span> React, { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

  <span class="hljs-comment">/**
   * Event form component.
   * 
   * @returns The event form component.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EventForm</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-comment">// Create a reference to the form element</span>
      <span class="hljs-keyword">const</span> ref = useRef&lt;HTMLFormElement&gt;(<span class="hljs-literal">null</span>);

      <span class="hljs-keyword">const</span> inputStyle = {
          color: <span class="hljs-string">'black'</span>,
          backgroundColor: <span class="hljs-string">'white'</span>,
          border: <span class="hljs-string">'1px solid black'</span>,
          padding: <span class="hljs-string">'8px'</span>,
          display: <span class="hljs-string">'block'</span>,
          width: <span class="hljs-string">'100%'</span>,
          borderRadius: <span class="hljs-string">'5px'</span>,
      };

      <span class="hljs-keyword">return</span> (
          &lt;div className=<span class="hljs-string">'container mx-auto px-4 sm:px-8 md:px-16 lg:px-24'</span>&gt;
              &lt;h2 className=<span class="hljs-string">'text-center m-4 text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-bold'</span>&gt;Add Event&lt;/h2&gt;
              &lt;form className=<span class="hljs-string">'space-y-4'</span> autoComplete=<span class="hljs-string">"off"</span> ref={ref} action={<span class="hljs-keyword">async</span> (FormData) =&gt; {
                  ref.current?.reset();
                  <span class="hljs-keyword">await</span> createEvent(FormData);
              }}&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"title"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Title&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"title"</span> id=<span class="hljs-string">'title'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"description"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Description&lt;/label&gt;
                      &lt;textarea id=<span class="hljs-string">'description'</span> name=<span class="hljs-string">"description"</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"date"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;<span class="hljs-built_in">Date</span>&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"date"</span> name=<span class="hljs-string">"date"</span> id=<span class="hljs-string">'date'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"address"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Address&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"address"</span> id=<span class="hljs-string">'address'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"city"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;City&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"city"</span> id=<span class="hljs-string">'city'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"state"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;State&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"state"</span> id=<span class="hljs-string">'state'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"zip"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Zip&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"zip"</span> id=<span class="hljs-string">'zip'</span> style={inputStyle} required /&gt;
                  &lt;/div&gt;
                  &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">'submit'</span> className=<span class="hljs-string">'hover:bg-gradient-to-r from-splash to-razzmatazz hover:text-black inline-flex justify-center py-2 px-4 sm:px-6 md:px-8 lg:px-10 border border-transparent shadow-sm text-sm sm:text-base md:text-lg lg:text-xl font-medium rounded-md text-white'</span>&gt;Submit&lt;/button&gt;            
              &lt;/form&gt;
          &lt;/div&gt;
      );
  };
</code></pre>
<ul>
<li><p>This component is used in the <code>/artists</code> page, and imports the server action for creating events, as well as the useRef React Hook</p>
</li>
<li><p>First, I created a reference to the form element with useRef, and this reference will be used later on to reset the form fields after submission</p>
</li>
<li><p>The component returns a form where the action attribute is set to an async function that first resets the form, then calls createEvent with the form data</p>
</li>
<li><p>The form includes several input fields for title, description, address, city, state, and zip.</p>
</li>
</ul>
</li>
<li><p>EventList - A server component that effectively fetches and displays events in a user-friendly manner, ensuring a responsive and organized presentation of event details</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { getEvents } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/action"</span>;

  <span class="hljs-comment">/**
   * Get all events.
   * 
   * @returns All events.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetEvents</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">try</span> {
          <span class="hljs-comment">// Get all events</span>
          <span class="hljs-keyword">const</span> events = <span class="hljs-keyword">await</span> getEvents();
          <span class="hljs-keyword">if</span> (events.length === <span class="hljs-number">0</span>) {
              <span class="hljs-keyword">return</span> &lt;h1&gt;No Events&lt;/h1&gt;;
          } <span class="hljs-keyword">else</span> {
              <span class="hljs-keyword">return</span> (
                  &lt;div className=<span class="hljs-string">'grid grid-rows-1 md:grid-rows-2 lg:grid-rows-3 gap-5'</span>&gt;
                      {events.map(<span class="hljs-function">(<span class="hljs-params">event: <span class="hljs-built_in">any</span></span>) =&gt;</span> (
                          &lt;div key={event._id} className=<span class="hljs-string">'p-5 border rounded shadow-md'</span>&gt;
                              &lt;h3 className=<span class="hljs-string">'text-lg text-center md:text-xl lg:text-2xl font-bold'</span>&gt;{event.title <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/h3&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;Description:&lt;<span class="hljs-regexp">/b&gt; {event.description as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;<span class="hljs-built_in">Date</span>:&lt;<span class="hljs-regexp">/b&gt; {event.date as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;&lt;b&gt;Address:&lt;<span class="hljs-regexp">/b&gt; {event.address as string}&lt;/</span>p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.city <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.state <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                              &lt;p className=<span class="hljs-string">'text-sm md:text-base lg:text-lg'</span>&gt;{event.zip <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>}&lt;/p&gt;
                          &lt;/div&gt;
                      ))}
                  &lt;/div&gt;
              );
          }
      } <span class="hljs-keyword">catch</span> (error) {
          <span class="hljs-built_in">console</span>.log(error);
      }
  };
</code></pre>
<ul>
<li><p>This component is used in the <code>/users</code> page, and imports the server action for fetching events</p>
</li>
<li><p>First, a call is made to getEvents to fetch the list of events. If the array is empty, it returns HTML stating that there are no events</p>
</li>
<li><p>If there are events in the array, each event is mapped to a <code>div</code> with the key attribute set to the event's ObjectID, with child elements to display the title, description, date, address, city, state, and zip.</p>
</li>
<li><p>The events are displayed in a responsive grid layout that adjusts the number of rows based on the screen size.</p>
</li>
</ul>
</li>
<li><p>Map - A client component that provides a dynamic and interactive map that displays event locations with markers, enhancing the user experience with geocoding and responsive design</p>
<pre><code class="lang-typescript">  <span class="hljs-string">'use client'</span>
  <span class="hljs-keyword">import</span> React, { useCallback, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { GoogleMap, Marker, useJsApiLoader} <span class="hljs-keyword">from</span> <span class="hljs-string">'@react-google-maps/api'</span>;
  <span class="hljs-keyword">import</span> { Event } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/types/event'</span>;

  <span class="hljs-keyword">const</span> mapContainerStyle = {
      width: <span class="hljs-string">'100%'</span>,
      height: <span class="hljs-string">'100%'</span>
  };

  <span class="hljs-comment">// Map component props</span>
  <span class="hljs-keyword">interface</span> MapProps {
      events: Event[];
  }

  <span class="hljs-keyword">const</span> nightModeStyles = [
      { elementType: <span class="hljs-string">"geometry"</span>, stylers: [{ color: <span class="hljs-string">"#242f3e"</span> }] },
      { elementType: <span class="hljs-string">"labels.text.stroke"</span>, stylers: [{ color: <span class="hljs-string">"#242f3e"</span> }] },
      { elementType: <span class="hljs-string">"labels.text.fill"</span>, stylers: [{ color: <span class="hljs-string">"#746855"</span> }] },
      {
        featureType: <span class="hljs-string">"administrative.locality"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#d59563"</span> }],
      },
      {
        featureType: <span class="hljs-string">"poi"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#d59563"</span> }],
      },
      {
        featureType: <span class="hljs-string">"poi.park"</span>,
        elementType: <span class="hljs-string">"geometry"</span>,
        stylers: [{ color: <span class="hljs-string">"#263c3f"</span> }],
      },
      {
        featureType: <span class="hljs-string">"poi.park"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#6b9a76"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road"</span>,
        elementType: <span class="hljs-string">"geometry"</span>,
        stylers: [{ color: <span class="hljs-string">"#38414e"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road"</span>,
        elementType: <span class="hljs-string">"geometry.stroke"</span>,
        stylers: [{ color: <span class="hljs-string">"#212a37"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#9ca5b3"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road.highway"</span>,
        elementType: <span class="hljs-string">"geometry"</span>,
        stylers: [{ color: <span class="hljs-string">"#746855"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road.highway"</span>,
        elementType: <span class="hljs-string">"geometry.stroke"</span>,
        stylers: [{ color: <span class="hljs-string">"#1f2835"</span> }],
      },
      {
        featureType: <span class="hljs-string">"road.highway"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#f3d19c"</span> }],
      },
      {
        featureType: <span class="hljs-string">"transit"</span>,
        elementType: <span class="hljs-string">"geometry"</span>,
        stylers: [{ color: <span class="hljs-string">"#2f3948"</span> }],
      },
      {
        featureType: <span class="hljs-string">"transit.station"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#d59563"</span> }],
      },
      {
        featureType: <span class="hljs-string">"water"</span>,
        elementType: <span class="hljs-string">"geometry"</span>,
        stylers: [{ color: <span class="hljs-string">"#17263c"</span> }],
      },
      {
        featureType: <span class="hljs-string">"water"</span>,
        elementType: <span class="hljs-string">"labels.text.fill"</span>,
        stylers: [{ color: <span class="hljs-string">"#515c6d"</span> }],
      },
      {
        featureType: <span class="hljs-string">"water"</span>,
        elementType: <span class="hljs-string">"labels.text.stroke"</span>,
        stylers: [{ color: <span class="hljs-string">"#17263c"</span> }],
      },
  ];

  <span class="hljs-comment">/**
   * Map component.
   * 
   * @param {MapProps} props Map component props.
   * @returns {JSX.Element} Map component.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Map</span>(<span class="hljs-params">{ events }: MapProps</span>) </span>{
      <span class="hljs-keyword">let</span> geocoder: google.maps.Geocoder;
      <span class="hljs-keyword">const</span> [geocodedEvents, setGeocodedEvents] = useState(events);

      <span class="hljs-comment">/**
       * Geocode the events.
       * 
       * @returns {void}
       * @throws {Error} Geocoding failed for address.
       * @returns {Promise&lt;Event[]&gt;} The geocoded events.
       */</span>
      <span class="hljs-keyword">const</span> geocode = useCallback(<span class="hljs-function">() =&gt;</span> {
          geocoder = <span class="hljs-keyword">new</span> google.maps.Geocoder();

          <span class="hljs-comment">// Geocode the events</span>
          <span class="hljs-keyword">const</span> geocodePromises: <span class="hljs-built_in">Promise</span>&lt;Event&gt;[] = events.map(<span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
              <span class="hljs-keyword">const</span> address = <span class="hljs-string">`<span class="hljs-subst">${event.address}</span>, <span class="hljs-subst">${event.city}</span>, <span class="hljs-subst">${event.state}</span> <span class="hljs-subst">${event.zip}</span>`</span>;
              geocoder.geocode({ address: address }, <span class="hljs-function">(<span class="hljs-params">results, status</span>) =&gt;</span> {
                  <span class="hljs-keyword">if</span> (status === <span class="hljs-string">'OK'</span> &amp;&amp; results !== <span class="hljs-literal">null</span>) {
                      event.latitude = results[<span class="hljs-number">0</span>].geometry.location.lat().toString();
                      event.longitude = results[<span class="hljs-number">0</span>].geometry.location.lng().toString();
                      resolve(event);
                  } <span class="hljs-keyword">else</span> {
                      reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Geocoding failed for address: <span class="hljs-subst">${event.address}</span>`</span>));
                  }
              });
          }));
          <span class="hljs-comment">// Set the geocoded events</span>
          <span class="hljs-built_in">Promise</span>.all(geocodePromises)
              .then(<span class="hljs-function"><span class="hljs-params">geocodedEvents</span> =&gt;</span> {
                  setGeocodedEvents(geocodedEvents);
              })
              .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
      }, [events]);

      <span class="hljs-comment">// Load the Google Maps API</span>
      <span class="hljs-keyword">const</span> { isLoaded } = useJsApiLoader({
          id: <span class="hljs-string">'google-map-script'</span>,
          googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!,
      })

      <span class="hljs-keyword">return</span> (
          &lt;div className=<span class="hljs-string">'w-full h-64 sm:h-96 md:h-128 lg:h-256'</span>&gt;
              {isLoaded &amp;&amp; &lt;GoogleMap options={{ styles: nightModeStyles }} mapContainerStyle={mapContainerStyle} center={
                  {
                      lat: <span class="hljs-built_in">parseFloat</span>(geocodedEvents[<span class="hljs-number">0</span>].latitude) || <span class="hljs-number">0</span>,
                      lng: <span class="hljs-built_in">parseFloat</span>(geocodedEvents[<span class="hljs-number">0</span>].longitude) || <span class="hljs-number">0</span>
                  }
              } zoom={<span class="hljs-number">4</span>} onLoad={geocode}&gt;
                  {geocodedEvents.map(<span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> (
                      &lt;Marker key={event._id} position={{ lat: <span class="hljs-built_in">parseFloat</span>(event.latitude), lng: <span class="hljs-built_in">parseFloat</span>(event.longitude) }} /&gt;
                  ))}
              &lt;/GoogleMap&gt;}
          &lt;/div&gt;
      );
  }
</code></pre>
<ul>
<li><p>This component is used in the <code>/users</code> page, and imports the event interface, the useCallback and useState React Hooks, as well as the GoogleMap, Marker, and useJsApiLoader components from the react-google-maps/api library</p>
</li>
<li><p>First, I defined the map component properties which is an array of events where each event is of type Event (as defined and imported by the event interface)</p>
</li>
<li><p>Next, I set up a function to geocode the addresses (the Google Maps API requires longitude and latitude data to place markers on a mp)</p>
</li>
<li><p>The geocode function uses the useCallback hook, and maps over the events array and creates a promise for each event to geocode its address</p>
</li>
<li><p>If geocoding is successful, it updates the event's latitude and longitude</p>
</li>
<li><p>If geocoding fails, it rejects the promise with an error</p>
</li>
<li><p><code>Promise.all</code> is used to wait for all geocoding promises to resolve, and the geocodedEvents state is updated with the results</p>
</li>
<li><p>The component then returns a <code>div</code> with responsive height classes</p>
</li>
<li><p>If the Google Maps API is loaded, it renders a GoogleMap component with the following properties</p>
<ul>
<li><p>options: sets the map styles to nightModeStyles</p>
</li>
<li><p>mapContainerStyle: sets the container style to mapContainerStyle</p>
</li>
<li><p>center: sets the initial center of the map to the latitude and longitude of the first geocoded event</p>
</li>
<li><p>zoom: sets the initial zoom level to 4</p>
</li>
<li><p>onLoad: calls the geocode function when the map loads</p>
</li>
</ul>
</li>
<li><p>Inside the GoogleMap component, it maps over the geocodedEvents array and renders a marker for each event at its geocoded position</p>
</li>
</ul>
</li>
<li><p>ToggleMenu - A client component that provides a responsive and interactive header, enhancing the user experience with a mobile-friendly navigation menu</p>
<pre><code class="lang-typescript">  <span class="hljs-string">'use client'</span>;
  <span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { usePathname } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/navigation'</span>;
  <span class="hljs-keyword">import</span> { FaBars, FaTimes } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-icons/fa'</span>;
  <span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>;

  <span class="hljs-comment">/**
   * Header component.
   * 
   * @returns {JSX.Element} Header component.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">const</span> [isOpen, setIsOpen] = useState(<span class="hljs-literal">false</span>);
      <span class="hljs-keyword">const</span> pathname = usePathname();

      <span class="hljs-keyword">const</span> toggleMenu = <span class="hljs-function">() =&gt;</span> {
          setIsOpen(!isOpen);
      };

      <span class="hljs-comment">// Close the menu when the path changes</span>
      useEffect(<span class="hljs-function">() =&gt;</span> {
          setIsOpen(<span class="hljs-literal">false</span>);
      }, [pathname]);

      <span class="hljs-keyword">return</span> (
          &lt;header className=<span class="hljs-string">"bg-gradient-to-r from-splash to-razzmatazz text-black p-4"</span>&gt;
              &lt;div className=<span class="hljs-string">"container mx-auto flex justify-between items-center"</span>&gt;
                  &lt;h1 className=<span class="hljs-string">"text-2xl font-bold"</span>&gt;TikTok Concerts&lt;/h1&gt;
                  &lt;div className=<span class="hljs-string">"text-2xl lg:hidden"</span> onClick={toggleMenu}&gt;
                      {isOpen ? &lt;FaTimes /&gt; : &lt;FaBars /&gt;}
                  &lt;/div&gt;
                  &lt;nav className={<span class="hljs-string">`hidden lg:flex space-x-4`</span>}&gt;
                      &lt;Link href=<span class="hljs-string">"/"</span> className=<span class="hljs-string">"hover:underline font-bold p-2"</span>&gt;Home&lt;/Link&gt;
                      &lt;Link href=<span class="hljs-string">"/about"</span> className=<span class="hljs-string">"hover:underline font-bold p-2"</span>&gt;About&lt;/Link&gt;
                      &lt;Link href=<span class="hljs-string">"/users"</span> className=<span class="hljs-string">"hover:underline font-bold p-2"</span>&gt;Users&lt;/Link&gt;
                      &lt;Link href=<span class="hljs-string">"/artists"</span> className=<span class="hljs-string">"hover:underline font-bold p-2"</span>&gt;Artists&lt;/Link&gt;
                      &lt;Link target=<span class="hljs-string">"_blank"</span> href=<span class="hljs-string">"https://github.com/sirus-the-beaver/tiktok-concerts"</span> className=<span class="hljs-string">"hover:underline font-bold p-2"</span>&gt;GitHub Repo&lt;/Link&gt;
                  &lt;/nav&gt;
              &lt;/div&gt;
              {isOpen &amp;&amp; (
                  &lt;nav className=<span class="hljs-string">"bg-gray-800 lg:hidden"</span>&gt;
                      &lt;ul className=<span class="hljs-string">"flex flex-col items-center space-y-2 p-4"</span>&gt;
                          &lt;li&gt;&lt;Link href=<span class="hljs-string">"/"</span> className=<span class="hljs-string">"hover:underline font-bold block p-2"</span>&gt;Home&lt;<span class="hljs-regexp">/Link&gt;&lt;/</span>li&gt;
                          &lt;li&gt;&lt;Link href=<span class="hljs-string">"/about"</span> className=<span class="hljs-string">"hover:underline font-bold block p-2"</span>&gt;About&lt;<span class="hljs-regexp">/Link&gt;&lt;/</span>li&gt;
                          &lt;li&gt;&lt;Link href=<span class="hljs-string">"/users"</span> className=<span class="hljs-string">"hover:underline font-bold block p-2"</span>&gt;Users&lt;<span class="hljs-regexp">/Link&gt;&lt;/</span>li&gt;
                          &lt;li&gt;&lt;Link href=<span class="hljs-string">"/artists"</span> className=<span class="hljs-string">"hover:underline font-bold block p-2"</span>&gt;Artists&lt;<span class="hljs-regexp">/Link&gt;&lt;/</span>li&gt;
                          &lt;li&gt;&lt;Link target=<span class="hljs-string">"_blank"</span> href=<span class="hljs-string">"https://github.com/sirus-the-beaver/tiktok-concerts"</span> className=<span class="hljs-string">"hover:underline font-bold block p-2"</span>&gt;GitHub Repo&lt;<span class="hljs-regexp">/Link&gt;&lt;/</span>li&gt;
                      &lt;/ul&gt;
                  &lt;/nav&gt;
              )}
          &lt;/header&gt;
      );
  };
</code></pre>
<ul>
<li><p>This component is used in the root app layout, and imports the useState and useEffect React Hooks, the usePathname Next.js component, the FaBars and FaTimes React icons, and the Link React component</p>
</li>
<li><p>First, I set a state variable, isOpen, to false to manage the menu's open/close state</p>
</li>
<li><p>Next, I define the toggleMenu function which toggles the isOpen state between true and false</p>
</li>
<li><p>The useEffect hook is used to close the menu whenever the path changes (a user clicks a link to go to another page)</p>
</li>
<li><p>The component returns a header element with a <code>div</code> for the menu icon that toggles the menu on click, visible only on smaller screens, as well as a <code>nav</code> that is visible only on larger screens</p>
</li>
<li><p>If isOpen is true, a secondary <code>nav</code> is rendered for smaller screens</p>
</li>
<li><p>The header is responsive, with different navigation layouts for larger and smaller screens</p>
</li>
</ul>
</li>
<li><p>UpdateEventForm - A client component that provides a user-friendly interface for updating an existing event, with responsive design and consistent styling</p>
<pre><code class="lang-typescript">  <span class="hljs-string">'use client'</span>;
  <span class="hljs-keyword">import</span> { updateEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/lib/action'</span>;
  <span class="hljs-keyword">import</span> React, { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/navigation'</span>;

  <span class="hljs-comment">/**
   * Update event form component.
   * 
   * @returns The update event form component.
   */</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UpdateEventForm</span>(<span class="hljs-params">{eventId}: {eventId: <span class="hljs-built_in">string</span>}</span>) </span>{
      <span class="hljs-keyword">const</span> ref = useRef&lt;HTMLFormElement&gt;(<span class="hljs-literal">null</span>);

      <span class="hljs-keyword">const</span> inputStyle = {
          color: <span class="hljs-string">'black'</span>,
          backgroundColor: <span class="hljs-string">'white'</span>,
          border: <span class="hljs-string">'1px solid black'</span>,
          padding: <span class="hljs-string">'8px'</span>,
          display: <span class="hljs-string">'block'</span>,
          width: <span class="hljs-string">'100%'</span>,
          borderRadius: <span class="hljs-string">'5px'</span>,
      };

      <span class="hljs-comment">/** 
       * Handle the form submission.
       * 
       * @param FormData - The form data.
       * 
       * @returns The updated event.
      */</span>
      <span class="hljs-keyword">const</span> actionHandler = <span class="hljs-keyword">async</span> (FormData: <span class="hljs-built_in">any</span>) =&gt; {
          ref.current?.reset();
          <span class="hljs-keyword">await</span> updateEvent(FormData);

          redirect(<span class="hljs-string">'/artists'</span>);
      }

      <span class="hljs-keyword">return</span> (
          &lt;div className=<span class="hljs-string">'container mx-auto px-4 sm:px-8 md:px-16 lg:px-24'</span>&gt;
              &lt;h2 className=<span class="hljs-string">'text-center m-4 text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-bold'</span>&gt;Update Event&lt;/h2&gt;
              &lt;form autoComplete=<span class="hljs-string">"off"</span> className=<span class="hljs-string">'space-y-4'</span> ref={ref} action={actionHandler}&gt;
                  &lt;input hidden <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"id"</span> id=<span class="hljs-string">'id'</span> defaultValue={eventId}/&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"title"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Title&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"title"</span> id=<span class="hljs-string">'title'</span> style={inputStyle}/&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"description"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Description&lt;/label&gt;
                      &lt;textarea id=<span class="hljs-string">'description'</span> name=<span class="hljs-string">"description"</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"date"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;<span class="hljs-built_in">Date</span>&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"date"</span> name=<span class="hljs-string">"date"</span> id=<span class="hljs-string">'date'</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"address"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Address&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"address"</span> id=<span class="hljs-string">'address'</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"city"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;City&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"city"</span> id=<span class="hljs-string">'city'</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"state"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;State&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"state"</span> id=<span class="hljs-string">'state'</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;label htmlFor=<span class="hljs-string">"zip"</span> className=<span class="hljs-string">'block text-sm sm:text-base md:text-lg lg:text-xl font-medium text-gray-700'</span>&gt;Zip&lt;/label&gt;
                      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"zip"</span> id=<span class="hljs-string">'zip'</span> style={inputStyle} /&gt;
                  &lt;/div&gt;
                  &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">'submit'</span> className=<span class="hljs-string">'hover:bg-gradient-to-r from-splash to-razzmatazz hover:text-black inline-flex justify-center py-2 px-4 sm:px-6 md:px-8 lg:px-10 border border-transparent shadow-sm text-sm sm:text-base md:text-lg lg:text-xl font-medium rounded-md text-white'</span>&gt;Update&lt;<span class="hljs-regexp">/button&gt;            &lt;/</span>form&gt;
          &lt;/div&gt;
      )
  }
</code></pre>
<ul>
<li><p>This component is used in the <code>/update</code> page, and imports the server action for updating events, as well as the useRef React Hook, and the redirect function from Next.js</p>
</li>
<li><p>First, I defined a reference to the form with useRef, which will be used later on to reset the form after submission</p>
</li>
<li><p>Next, I define the actionHandler function which is an async function that handles the form submission. It resets the form fields, calls updateEvent with the form data, and then redirects the user to the <code>/artists</code> page after the event is updated</p>
</li>
<li><p>The component returns a form with the action attribute set to the actionHandler function</p>
</li>
<li><p>The form includes several input fields including, ID (a hidden input field for the event ID, pre-filled with the eventId prop), title, description, date, address, city, state, and zip</p>
</li>
<li><p>The form fields are not marked as required, allowing for partial updates</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-defining-the-server-actions">Defining the server actions</h3>
<p>Within my <code>src</code> directory, I created another directory called <code>lib</code>, where I added a file named <code>action.ts</code> that contains the server actions.</p>
<pre><code class="lang-typescript"><span class="hljs-string">'use server'</span>;
<span class="hljs-keyword">import</span> Event <span class="hljs-keyword">from</span> <span class="hljs-string">"@/models/Event"</span>;
<span class="hljs-keyword">import</span> { revalidatePath } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/cache"</span>;
<span class="hljs-keyword">import</span> { connectToDatabase } <span class="hljs-keyword">from</span> <span class="hljs-string">"./db"</span>;

<span class="hljs-comment">/**
 * Get all events.
 * 
 * @returns The events.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getEvents</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">await</span> connectToDatabase();

    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> Event.find();
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(data));
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
        <span class="hljs-keyword">return</span> [];
    }
}

<span class="hljs-comment">/**
 * Create a new event.
 * 
 * @param formData - The form data.
 * 
 * @returns The new event.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createEvent</span>(<span class="hljs-params">formData: FormData</span>) </span>{
    <span class="hljs-comment">// Connect to the database</span>
    <span class="hljs-keyword">await</span> connectToDatabase();

    <span class="hljs-comment">// Get the form data</span>
    <span class="hljs-keyword">const</span> title = formData.get(<span class="hljs-string">'title'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> description = formData.get(<span class="hljs-string">'description'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> date = formData.get(<span class="hljs-string">'date'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> address = formData.get(<span class="hljs-string">'address'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> city = formData.get(<span class="hljs-string">'city'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> state = formData.get(<span class="hljs-string">'state'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;
    <span class="hljs-keyword">const</span> zip = formData.get(<span class="hljs-string">'zip'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;

    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// Create a new event</span>
        <span class="hljs-keyword">const</span> newEvent = <span class="hljs-keyword">await</span> Event.create({
            title,
            description,
            date,
            address,
            city,
            state,
            zip
        });

        newEvent.save();

        <span class="hljs-comment">// Update the events page with the new event</span>
        revalidatePath(<span class="hljs-string">'/artists'</span>);
        revalidatePath(<span class="hljs-string">'/users'</span>);
        <span class="hljs-keyword">return</span> newEvent.toString();
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
        <span class="hljs-keyword">return</span>{message: <span class="hljs-string">'Failed to create a new event'</span>};
    }
};

<span class="hljs-comment">/**
 * Delete an event.
 * 
 * @param id - The event id.
 * 
 * @returns The deleted event.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteEvent</span>(<span class="hljs-params">id: FormData</span>) </span>{
    <span class="hljs-keyword">await</span> connectToDatabase();
    <span class="hljs-keyword">const</span> eventId = id.get(<span class="hljs-string">'id'</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;

    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> Event.deleteOne({ _id: eventId });
        revalidatePath(<span class="hljs-string">'/artists'</span>);
        revalidatePath(<span class="hljs-string">'/users'</span>);
        <span class="hljs-keyword">return</span> (<span class="hljs-string">`Successfully deleted event with id <span class="hljs-subst">${eventId}</span>`</span>);
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">return</span> {message: <span class="hljs-string">'Failed to delete event'</span>};
    }
};

<span class="hljs-comment">/**
 * Update an event.
 * 
 * @param formData - The form data.
 * 
 * @returns The updated event.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateEvent</span>(<span class="hljs-params">formData: FormData</span>) </span>{
    <span class="hljs-keyword">await</span> connectToDatabase();
    <span class="hljs-keyword">const</span> eventId = formData.get(<span class="hljs-string">'id'</span>);
    <span class="hljs-keyword">const</span> event = <span class="hljs-keyword">await</span> Event.findOne({ _id: eventId });
    <span class="hljs-keyword">const</span> formerTitle = event?.title;
    <span class="hljs-keyword">const</span> formerDescription = event?.description;
    <span class="hljs-keyword">const</span> formerDate = event?.date;
    <span class="hljs-keyword">const</span> formerAddress = event?.address;
    <span class="hljs-keyword">const</span> formerCity = event?.city;
    <span class="hljs-keyword">const</span> formerState = event?.state;
    <span class="hljs-keyword">const</span> formerZip = event?.zip;

    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> Event.updateOne({ _id: eventId },
            {
                title: formData.get(<span class="hljs-string">'title'</span>) === <span class="hljs-string">''</span> ? formerTitle : formData.get(<span class="hljs-string">'title'</span>),
                description: formData.get(<span class="hljs-string">'description'</span>) === <span class="hljs-string">''</span> ? formerDescription : formData.get(<span class="hljs-string">'description'</span>),
                date: formData.get(<span class="hljs-string">'date'</span>) === <span class="hljs-string">''</span> ? formerDate : formData.get(<span class="hljs-string">'date'</span>),
                address: formData.get(<span class="hljs-string">'address'</span>) === <span class="hljs-string">''</span> ? formerAddress : formData.get(<span class="hljs-string">'address'</span>),
                city: formData.get(<span class="hljs-string">'city'</span>) === <span class="hljs-string">''</span> ? formerCity : formData.get(<span class="hljs-string">'city'</span>),
                state: formData.get(<span class="hljs-string">'state'</span>) === <span class="hljs-string">''</span> ? formerState : formData.get(<span class="hljs-string">'state'</span>),
                zip: formData.get(<span class="hljs-string">'zip'</span>) === <span class="hljs-string">''</span> ? formerZip : formData.get(<span class="hljs-string">'zip'</span>)
            }
        );
        revalidatePath(<span class="hljs-string">'/artists'</span>);
        revalidatePath(<span class="hljs-string">'/users'</span>);
        <span class="hljs-keyword">return</span> (<span class="hljs-string">`Successfully updated event with id <span class="hljs-subst">${eventId}</span>`</span>);
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">return</span> {message: <span class="hljs-string">'Failed to update event'</span>};
    }
};
</code></pre>
<p>I started by importing the database event model, the revalidatePath function from Next.js, and a function that I created to connect to the MongoDB database.</p>
<p>The file contains the following server actions:</p>
<ul>
<li><p>getEvents</p>
<ul>
<li><p>Fetches all events from the database</p>
</li>
<li><p>It first connects to the database, then tries to fetch all events</p>
</li>
<li><p>The fetched data is returned after converting it to JSON format</p>
</li>
<li><p>If an error occurs, it logs the error and returns an empty array</p>
</li>
</ul>
</li>
<li><p>createEvent</p>
<ul>
<li><p>Creates a new event in the database</p>
</li>
<li><p>It first connects to the database, then extracts form data from the formData object</p>
</li>
<li><p>Next, it tries to create a new event and saves it</p>
</li>
<li><p>After creating the event, it revalidates the paths <code>/artists</code> and <code>/users</code> to purge cached data and update the events page (this step is necessary due to Next.js's client side router cache)</p>
</li>
</ul>
</li>
<li><p>deleteEvent</p>
<ul>
<li><p>Deletes an event from the database</p>
</li>
<li><p>It first connects to the database, then extracts the event's ObjectID from the id form data</p>
</li>
<li><p>It then tries to delete the event, and afterwards, it revalidates the paths <code>/artists</code> and <code>/users</code></p>
</li>
<li><p>updateEvent</p>
<ul>
<li><p>Updates an existing event in the database</p>
</li>
<li><p>It first connects to the database, then extracts the event's ObjectID from the formData object</p>
</li>
<li><p>Next, it fetches the current event details so that any empty fields remain the same</p>
</li>
<li><p>It then tries to update the event, only changing fields that are not empty in the form data</p>
</li>
<li><p>After updating the event, it revalidates the paths <code>/artists</code> and <code>/users</code></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-connecting-to-the-database-and-designing-the-event-schema-and-model">Connecting to the database and designing the event schema and model</h3>
<p>Within the <code>lib</code> directory, I also created a file called <code>db.ts</code> where I define my function to connect to the database.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> mongoose, { Connection } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>;

<span class="hljs-comment">// Cache the connection to avoid connecting to the database multiple times</span>
<span class="hljs-keyword">let</span> cachedConnection: Connection | <span class="hljs-literal">null</span> = <span class="hljs-literal">null</span>;

<span class="hljs-comment">/**
 * Connect to the database.
 * 
 * @returns The connection to the database.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connectToDatabase</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (cachedConnection) {
        <span class="hljs-keyword">return</span> cachedConnection;
    }
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> cnx = <span class="hljs-keyword">await</span> mongoose.connect(process.env.MONGODB_URI!);

        cachedConnection = cnx.connection;

        <span class="hljs-keyword">return</span> cachedConnection;
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
        <span class="hljs-keyword">throw</span> error;
    };
};
</code></pre>
<p>First, I imported the mongoose library. Then, I created a variable named <code>cachedConnection</code> to store the database connection, preventing multiple reconnections.</p>
<p>The connectToDatabase function is an async function that first checks if cachedConnection is not null. If a cached connection exists, it returns the cached connection. Otherwise, it tries to connect to the MongoDB database and then caches the connection.</p>
<p>Within the <code>src</code> directory, I created another directory called <code>models</code> and added a file named <code>Event.ts</code>. This is where I defined the event schema and model.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> mongoose, { Document, Model } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> IEvent {
    title: <span class="hljs-built_in">string</span>;
    description: <span class="hljs-built_in">string</span>;
    date: <span class="hljs-built_in">string</span>;
    address: <span class="hljs-built_in">string</span>;
    city: <span class="hljs-built_in">string</span>;
    state: <span class="hljs-built_in">string</span>;
    zip: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> IEventDocument <span class="hljs-keyword">extends</span> IEvent, Document {
    _id: mongoose.Schema.Types.ObjectId;
    createdAt: <span class="hljs-built_in">Date</span>;
    updatedAt: <span class="hljs-built_in">Date</span>;
};

<span class="hljs-comment">// Create a new schema for events</span>
<span class="hljs-keyword">const</span> eventSchema = <span class="hljs-keyword">new</span> mongoose.Schema&lt;IEventDocument&gt;(
    {
        _id: { <span class="hljs-keyword">type</span>: mongoose.Schema.Types.ObjectId, auto: <span class="hljs-literal">true</span>},
        title: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        description: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        date: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        address: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        city: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        state: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
        zip: { <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> }
    },
    { timestamps: <span class="hljs-literal">true</span> }
);

<span class="hljs-comment">// Create a new model for events</span>
<span class="hljs-keyword">const</span> Event: Model&lt;IEventDocument&gt; = 
    mongoose.models?.Event || mongoose.model(<span class="hljs-string">'Event'</span>, eventSchema);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Event;
</code></pre>
<p>First, I imported the mongoose library. Then, I created a TypeScript interface that defines the structure of an event object.</p>
<p>Next, I created an interface that extends both IEvent and Document from mongoose which includes all properties from IEvent and adds _id (the ObjectID), createdAt, and updatedAt.</p>
<p>I then defined the eventSchema which is a mongoose schema for the IEventDocument interface. The schema defines the structure of the event documents in the database.</p>
<p>Finally, I created the Event model with the eventSchema, and check if a model named Event already exists to avoid redefining the model.</p>
<h2 id="heading-challenges-and-solutions">Challenges and Solutions</h2>
<h3 id="heading-handling-authentication">Handling authentication</h3>
<p>Authentication was supposed to be handled with the <strong>TikTok Login Kit</strong> using <strong>NextAuth.js</strong>, but I faced configuration issues that caused errors related to missing tokens and issuer definitions. After troubleshooting and checking GitHub, I decided to skip authentication for the initial release.</p>
<h3 id="heading-connection-to-the-database">Connection to the database</h3>
<p>During development, I didn't have any issues connecting to the database. However, during deployment, I faced problems with server actions and database requests. The server wasn't fetching data correctly from the database, leading to session timeouts.</p>
<p>The issues were resolved by:</p>
<ol>
<li><p>Ensuring the database connection was correctly established in each server action.</p>
</li>
<li><p>Revalidating pages after server actions to clear cached data.</p>
</li>
</ol>
<h2 id="heading-future-enhancements">Future Enhancements</h2>
<h3 id="heading-potential-features-to-add">Potential Features to Add</h3>
<p>Looking ahead, I plan to add several features to the project:</p>
<ul>
<li><p><strong>TikTok Authentication</strong>: Reattempting integration with the TikTok Login Kit.</p>
</li>
<li><p><strong>Enhanced Location Input</strong>: Allowing users to input just the name of a location rather than the full address.</p>
</li>
<li><p><strong>Notification System</strong>: Implementing a system to notify fans of upcoming concerts.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building the TikTok Concerts platform using Next.js has been an exciting and rewarding experience.</p>
<p>By leveraging the powerful features of Next.js, TypeScript, React, and Tailwind CSS, I was able to create a dynamic and responsive web application that aims to enhance the live concert experience on TikTok Live. Despite facing challenges with authentication, I successfully implemented key features such as event scheduling, a global events map, and user-friendly interfaces for both artists and fans.</p>
<p>Looking ahead, I plan to add more features like TikTok authentication, enhanced location input, and a notification system to further improve the platform.</p>
<p>This project not only showcases the potential of modern web technologies but also aims to foster greater engagement and interaction between artists and their fans on TikTok.</p>
<h3 id="heading-call-to-action">Call to action</h3>
<p>I hope you enjoyed learning about my project, TikTok Concerts. If you find it interesting and believe it can make a difference in enhancing live concert experiences on TikTok, I would greatly appreciate your support.</p>
<p>Please visit my website to explore the platform and see it in action: <a target="_blank" href="https://tiktok-concerts.vercel.app"><strong>TikTok Concerts</strong></a>.</p>
<p>Additionally, if you like my project, please consider voting for my submission in the TikTok TechJam hackathon. Your vote can help bring more visibility to the project and support its development. You can vote for my submission here: <a target="_blank" href="https://devpost.com/software/tiktok-concerts"><strong>Vote for TikTok Concerts</strong></a>.</p>
<p>Thank you for your support!</p>
]]></content:encoded></item><item><title><![CDATA[Reasons to Avoid Using "var" for Declaring Variables in JavaScript]]></title><description><![CDATA[Introduction

This article discusses the reasons to avoid using the 'var' keyword for variable declaration in JavaScript. It highlights the issues related to function-scoping, variable hoisting, and redeclaration without warnings that come with 'var'...]]></description><link>https://scrappedscript.com/reasons-to-avoid-using-var-for-declaring-variables-in-javascript</link><guid isPermaLink="true">https://scrappedscript.com/reasons-to-avoid-using-var-for-declaring-variables-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 16 Jan 2024 15:45:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1bNQVGzuy0U/upload/3fca3613486a39e55c7195ae735ac668.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>This article discusses the reasons to avoid using the 'var' keyword for variable declaration in JavaScript. It highlights the issues related to function-scoping, variable hoisting, and redeclaration without warnings that come with 'var'. In contrast, 'let' and 'const' are recommended for their benefits such as block-scoping, controlled hoisting, and protection against redeclaration. This leads to a more reliable and maintainable coding environment.</p>
</blockquote>
<hr />
<h2 id="heading-scope-of-variables-declared-with-var">Scope of variables declared with var</h2>
<p>Variables declared using the <code>var</code> keyword exhibit function-scoping behavior, which is different from the block-scoping behavior of variables declared with <code>let</code> or <code>const</code>. Function-scoped variables are accessible throughout the entire function in which they are declared, regardless of the block they are defined in. This can lead to unintended issues, especially when working with nested functions or blocks, as variables declared with <code>var</code> might be accessible in places where they were not intended to be used.</p>
<p>In contrast, block-scoped variables declared with <code>let</code> or <code>const</code> are only accessible within the block they are defined in, providing a more predictable and controlled environment for managing variable visibility and lifetime. This helps to reduce the likelihood of encountering bugs related to variable scope and makes the code easier to understand and maintain.</p>
<hr />
<h2 id="heading-variable-hoisting">Variable hoisting</h2>
<p>The second reason to avoid declaring variables with var is due to a phenomenon known as hoisting.</p>
<p>Hoisting is a phenomenon that takes place when all variable declarations are shifted, or hoisted, to the beginning of their respective scope before the code is executed. This process happens automatically by the JavaScript engine during the compilation phase. The consequence of hoisting is that variables declared with <code>var</code> can be accessed and manipulated before their actual declaration in the code, which can lead to unexpected results and make the code harder to understand and maintain.</p>
<p>In contrast, when using <code>let</code> and <code>const</code> for variable declarations, hoisting still occurs, but the variables are not initialized until their actual declaration is reached in the code. This creates a temporal dead zone (TDZ) between the beginning of the scope and the point of declaration, during which accessing or manipulating the variables would result in a ReferenceError. This behavior helps to prevent unintended consequences and encourages a more predictable coding environment.</p>
<hr />
<h2 id="heading-redeclaring-variables">Redeclaring variables</h2>
<p>The last significant reason to avoid using <code>var</code> when declaring variables in JavaScript lies in the fact that variables declared with <code>var</code> can be re-declared without any warnings or error messages. This lack of feedback can result in unintentional overwriting of variables, which may lead to unexpected behavior in your code and create hard-to-find bugs.</p>
<p>When a variable is re-declared using <code>var</code>, the original value is simply replaced with the new one, and the code continues to execute without any indication that something may have gone wrong. This can be particularly problematic in larger codebases or when working with multiple developers, as it increases the likelihood of accidentally overwriting a variable that was intended to remain constant throughout the code.</p>
<p>In contrast, using <code>let</code> or <code>const</code> to declare variables provides a safeguard against this issue. If you attempt to re-declare a variable that has already been declared with <code>let</code> or <code>const</code>, JavaScript will throw an error, alerting you to the potential problem and preventing the code from executing further until the issue is resolved. This behavior encourages more predictable and reliable coding practices, reducing the risk of unintended consequences and promoting a more stable development environment.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, although the <code>var</code> keyword in JavaScript was once the standard, its potential pitfalls make it less desirable compared to <code>let</code> and <code>const</code>.</p>
<p>The function-scoping behavior, hoisting peculiarities, and the possibility of re-declaration without warnings make <code>var</code> a less predictable and potentially riskier choice.</p>
<p>On the other hand, <code>let</code> and <code>const</code> provide block-scoping, controlled hoisting, and protection against re-declaration, fostering a more reliable and maintainable coding environment.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[How to Build a Web Scraper Using Python]]></title><description><![CDATA[Introduction

This article provides a step-by-step guide on building a web scraper using Python. It begins with understanding the URL structure of the target website, here CNN, and then importing necessary libraries like Selenium, requests, and Beaut...]]></description><link>https://scrappedscript.com/how-to-build-a-web-scraper-using-python</link><guid isPermaLink="true">https://scrappedscript.com/how-to-build-a-web-scraper-using-python</guid><category><![CDATA[Python]]></category><category><![CDATA[web scraping]]></category><category><![CDATA[selenium]]></category><category><![CDATA[BeautifulSoup]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 02 Jan 2024 16:33:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Skf7HxARcoc/upload/b904040e2579644fcaf3a8aa46bbb74d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>This article provides a step-by-step guide on building a web scraper using Python. It begins with understanding the URL structure of the target website, here CNN, and then importing necessary libraries like Selenium, requests, and BeautifulSoup. It explains how to load a URL and locate target elements using Selenium, along with error handling to avoid program crashes. The article also covers parsing the text of the articles using BeautifulSoup. Finally, it demonstrates the results by running the script and successfully scraping the text from a CNN article.</p>
</blockquote>
<h2 id="heading-discovering-url-structure-of-target-website">Discovering URL structure of target website</h2>
<p>Before you can begin building a web scraper, you first have to understand the structure of the URLs that you'll be targeting.</p>
<p>In this tutorial, we'll be scraping text from CNN articles. So we'll start by heading to cnn.com and seeing if there's any search bar on the main webpage.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704209139408/e2daa943-acab-43bf-93f3-47f509d12a6e.png" alt="cnn home webpage" class="image--center mx-auto" /></p>
<p>As we can see at the top right of the homepage, there's a little search icon. Let's next click on the icon and see where we're taken.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704209223471/f9c86a3e-d4d3-45af-b8bd-fee2459152f2.png" alt="cnn search bar" class="image--center mx-auto" /></p>
<p>After clicking the search icon, we're taken to this search bar. Let's next search for a term and then see what URL we're taken to.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704209300784/7a941a6d-1d70-487b-b8d0-01d5cd59c939.png" alt="programming search on cnn website" class="image--center mx-auto" /></p>
<p>We're taken to this page where the URL is: <a target="_blank" href="https://www.cnn.com/search?q=programming&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section">https://www.cnn.com/search?q=programming&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section</a>.</p>
<p>We can now identify the structure for our target URLs. First, we have the protocol (https), then the domain (cnn.com), followed by the search subdomain path (/search) and finally the queries. As we can see from the first query pair (q=programming), this is where our search term that we typed into the search bar is placed in the URL. All of the other query pairs are default and can remain constant for our project.</p>
<p>Therefore that means that the only part of the URL that will be variable is the query pair "q=<em>search term</em>".</p>
<p>Now that we know our target URL structure, let's start building our webscraper.</p>
<h2 id="heading-importing-necessary-libraries">Importing necessary libraries</h2>
<p>Let's start by importing all of the necessary library components that we'll be using.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
</code></pre>
<p>We'll be using Selenium for loading the target URL and basic navigation on the target URL's webpage. Next, we'll be using requests and BeautifulSoup to load the article and parse the article's text.</p>
<h2 id="heading-loading-the-url-using-selenium">Loading the URL using Selenium</h2>
<p>Next, we'll define our target URL structure, and load the target URL with Selenium.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_cnn</span>(<span class="hljs-params">search_term</span>):</span>

    URL = <span class="hljs-string">"https://www.cnn.com/search?q="</span> + search_term + <span class="hljs-string">"&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section="</span>

    <span class="hljs-comment"># Set up driver</span>
    options = Options()
    options.add_argument(<span class="hljs-string">"--headless"</span>)
    options.page_load_strategy = <span class="hljs-string">'eager'</span>
    driver = webdriver.Chrome(options=options)
    driver.get(URL)
</code></pre>
<p>As mentioned before, the only variable in our target URLs will be that search term, so we can just copy and paste the rest of the URL since those will remain constant.</p>
<p>Next, we're defining certain parts of the Options class taken from the Selenium module.</p>
<p>The <code>options.add_argument("--headless")</code> prevents the browser window from opening on the screen.</p>
<p>The <code>options.page_load_strategy = 'eager'</code> is changing the default value of "normal" to "eager". With "normal" as the value, the web driver will wait for all of the resources on a webpage to finish loading. On the other hand, "eager" just waits for basic HTML elements to load.</p>
<p>Finally, in the last 2 lines, we're setting up our Selenium WebDriver (a tool that allows us to load and navigate the webpage) and passing in our URL to the driver so it can start loading the webpage.</p>
<h2 id="heading-locating-target-elements-using-selenium">Locating target element(s) using Selenium</h2>
<p>Before we proceed with adding more code to our program, let's inspect the webpage we're taken to after searching for a term, and see how we can target the first article on the page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704210889425/b7fd458a-fb6d-4b6e-abf5-6c0e05cea568.png" alt="inspecting cnn search webpage" class="image--center mx-auto" /></p>
<p>If we inspect the image corresponding to the article, we see that the image has an anchor tag that directs users to the article. So we can simply target this anchor tag by choosing one of its classes (we'll choose the "container__link" class) for the driver to look for after the page has loaded.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_cnn</span>(<span class="hljs-params">search_term</span>):</span>

    URL = <span class="hljs-string">"https://www.cnn.com/search?q="</span> + search_term + <span class="hljs-string">"&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section="</span>

    <span class="hljs-comment"># Set up driver</span>

    <span class="hljs-comment"># Only load HTML</span>
    options = Options()
    options.add_argument(<span class="hljs-string">"--headless"</span>)
    options.page_load_strategy = <span class="hljs-string">'eager'</span>
    driver = webdriver.Chrome(options=options)
    driver.get(URL)

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Wait for the page to load</span>
        elem = WebDriverWait(driver, <span class="hljs-number">15</span>).until(
        EC.presence_of_element_located((By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)))

        <span class="hljs-comment"># Find the first article and click on it</span>
        article = driver.find_element(By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)
        article.click()
</code></pre>
<p>With the <code>elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.CLASS_NAME, "container__link")))</code> lines, we're telling the driver to wait for the page to load the page until it finds a HTML tag with that class name. Additionally, we're adding a parameter (the 15) to mean that if it's been 15 seconds, then we can just stop loading the page.</p>
<p>Finally, after the element has loaded, we're simply going to use Selenium's click function so that the driver can click on the anchor tag that was located (which will take us to the URL of the first article that's on the search page).</p>
<h3 id="heading-error-handling">Error handling</h3>
<p>If you notice in the above code, there's a try block. Let's add in some error handling for when there's a timeout error by using the TimeoutException included in the Selenium library.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_cnn</span>(<span class="hljs-params">search_term</span>):</span>

    URL = <span class="hljs-string">"https://www.cnn.com/search?q="</span> + search_term + <span class="hljs-string">"&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section="</span>

    <span class="hljs-comment"># Set up driver</span>

    <span class="hljs-comment"># Only load HTML</span>
    options = Options()
    options.add_argument(<span class="hljs-string">"--headless"</span>)
    options.page_load_strategy = <span class="hljs-string">'eager'</span>
    driver = webdriver.Chrome(options=options)
    driver.get(URL)

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Wait for the page to load</span>
        elem = WebDriverWait(driver, <span class="hljs-number">15</span>).until(
        EC.presence_of_element_located((By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)))

        <span class="hljs-comment"># Find the first article and click on it</span>
        article = driver.find_element(By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)
        article.click()

    <span class="hljs-keyword">except</span> TimeoutException <span class="hljs-keyword">as</span> e:
        results = <span class="hljs-string">"Page took too long to load"</span>
        <span class="hljs-keyword">return</span> results
</code></pre>
<p>With this error handling, we're simply preventing our program from crashing in the event that our target URL takes too long to load.</p>
<h2 id="heading-parsing-text-using-beautifulsoup">Parsing text using BeautifulSoup</h2>
<p>Before continuing with writing more code, let's now inspect the webpage for the CNN article to see how we can identify the headline of an article as well as of the main text of the article.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704212181847/ad5c0bde-31c5-4377-8a0d-b9cd5b4daa6d.png" alt="inspecting CNN article webpage" class="image--center mx-auto" /></p>
<p>As we can see, the headline for CNN articles is an h1 tag, so we can simply have BeautifulSoup parse the text of the h1 tag located on the webpage.</p>
<p>Next, let's identify the text of the article.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704212305217/7425e08d-a3c8-4ef2-9066-39647d4cdbcd.png" alt class="image--center mx-auto" /></p>
<p>As we can see, CNN puts a class name of "paragraph" for all of the paragraphs that contain the article text. So we can simply have BeautifulSoup grab all of the elements with the class of "paragraph" and then parse the text inside.</p>
<p>Finally, let's parse the text that's in the article that we're taken to by the driver.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_cnn</span>(<span class="hljs-params">search_term</span>):</span>

    URL = <span class="hljs-string">"https://www.cnn.com/search?q="</span> + search_term + <span class="hljs-string">"&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section="</span>

    <span class="hljs-comment"># Set up driver</span>

    <span class="hljs-comment"># Only load HTML</span>
    options = Options()
    options.add_argument(<span class="hljs-string">"--headless"</span>)
    options.page_load_strategy = <span class="hljs-string">'eager'</span>
    driver = webdriver.Chrome(options=options)
    driver.get(URL)

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Wait for the page to load</span>
        elem = WebDriverWait(driver, <span class="hljs-number">15</span>).until(
        EC.presence_of_element_located((By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)))

        <span class="hljs-comment"># Find the first article and click on it</span>
        article = driver.find_element(By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)
        article.click()

    <span class="hljs-keyword">except</span> TimeoutException <span class="hljs-keyword">as</span> e:
        results = <span class="hljs-string">"Page took too long to load"</span>
        <span class="hljs-keyword">return</span> results

    <span class="hljs-keyword">finally</span>:
        current_url = driver.current_url

        page = requests.get(current_url)
        soup = BeautifulSoup(page.content, <span class="hljs-string">'html.parser'</span>)
        headline = soup.find(<span class="hljs-string">'h1'</span>).get_text().strip()
        paragraphs = soup.find_all(class_=<span class="hljs-string">'paragraph'</span>)
        text = <span class="hljs-string">''</span>
        <span class="hljs-keyword">for</span> paragraph <span class="hljs-keyword">in</span> paragraphs:
            text += paragraph.text.strip()

        link = <span class="hljs-string">"Article found at: "</span> + current_url
        results = (headline, text, link)

        driver.quit()

    <span class="hljs-keyword">return</span> results
</code></pre>
<p>First, we're grabbing the current URL (the URL of the article that we're taken to by the driver) and we're sending a GET request using the requests library.</p>
<p>Next, we're using BeautifulSoup to parse the HTML on the page of the article.</p>
<p>As you can see for the paragraphs, we're using the <code>find_all()</code> method which will return a list of all of the elements that have the class of "paragraph". Therefore, in order to access the text within the paragraphs, we'll have to iterate over the list of paragraphs, parse the text for each of the paragraphs, and then add the pure text to a running string of text that we define before the for-loop.</p>
<p>Finally, we'll have the driver quit the browser session, and return our results as as tuple.</p>
<h2 id="heading-putting-it-all-together">Putting it all together</h2>
<p>Now that we finished writing our function, let's try running it as a script and see what we get.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver
<span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By
<span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait
<span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC
<span class="hljs-keyword">from</span> selenium.webdriver.chrome.options <span class="hljs-keyword">import</span> Options
<span class="hljs-keyword">from</span> selenium.common.exceptions <span class="hljs-keyword">import</span> TimeoutException
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_cnn</span>(<span class="hljs-params">search_term</span>):</span>

    URL = <span class="hljs-string">"https://www.cnn.com/search?q="</span> + search_term + <span class="hljs-string">"&amp;from=0&amp;size=10&amp;page=1&amp;sort=newest&amp;types=all&amp;section="</span>

    <span class="hljs-comment"># Set up driver</span>

    <span class="hljs-comment"># Only load HTML</span>
    options = Options()
    options.add_argument(<span class="hljs-string">"--headless"</span>)
    options.page_load_strategy = <span class="hljs-string">'eager'</span>
    driver = webdriver.Chrome(options=options)
    driver.get(URL)

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Wait for the page to load</span>
        elem = WebDriverWait(driver, <span class="hljs-number">15</span>).until(
        EC.presence_of_element_located((By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)))

        <span class="hljs-comment"># Find the first article and click on it</span>
        article = driver.find_element(By.CLASS_NAME, <span class="hljs-string">"container__link"</span>)
        article.click()

    <span class="hljs-keyword">except</span> TimeoutException <span class="hljs-keyword">as</span> e:
        results = <span class="hljs-string">"Page took too long to load"</span>
        <span class="hljs-keyword">return</span> results

    <span class="hljs-keyword">finally</span>:
        current_url = driver.current_url

        page = requests.get(current_url)
        soup = BeautifulSoup(page.content, <span class="hljs-string">'html.parser'</span>)
        headline = soup.find(<span class="hljs-string">'h1'</span>).get_text().strip()
        paragraphs = soup.find_all(class_=<span class="hljs-string">'paragraph'</span>)
        text = <span class="hljs-string">''</span>
        <span class="hljs-keyword">for</span> paragraph <span class="hljs-keyword">in</span> paragraphs:
            text += paragraph.text.strip()

        link = <span class="hljs-string">"Article found at: "</span> + current_url
        results = (headline, text, link)

        driver.quit()

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


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    SEARCH_TERM = <span class="hljs-string">'programming'</span>
    print(search_cnn(SEARCH_TERM))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704212725712/c8a6420e-baf1-4818-b961-c4f3e3f8a154.png" alt="output of running python script" class="image--center mx-auto" /></p>
<p>After running the script, we see all of the article text (along with the headline and link) printed out beautifully in the terminal.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we walked through the steps of creating a web scraper using Python. We started with understanding the URL structure of our target website (CNN) and then proceeded to import necessary libraries like Selenium, requests, and BeautifulSoup.</p>
<p>We learned how to load a URL and locate target elements using Selenium. We also discussed error handling to avoid program crashes. Then, we parsed the text of the articles using BeautifulSoup.</p>
<p>Finally, we put it all together and ran our script, successfully scraping the text from a CNN article. This process showcases how Python can be very powerful in web scraping, opening up a wide range of possibilities for data collection and analysis.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Assessing GitHub Copilot: A Candid Overview]]></title><description><![CDATA[Introduction
In case you're not familiar, GitHub Copilot is GitHub's "AI pair programmer" that provides intelligent code completion and a chatbot capable of answering any programming-related questions.
The concept behind GitHub Copilot is to enable d...]]></description><link>https://scrappedscript.com/assessing-github-copilot-a-candid-overview</link><guid isPermaLink="true">https://scrappedscript.com/assessing-github-copilot-a-candid-overview</guid><category><![CDATA[copilot]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Sat, 30 Dec 2023 02:23:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UT8LMo-wlyk/upload/6585adde93b70e5db702a81ce15e6e1b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In case you're not familiar, GitHub Copilot is GitHub's "AI pair programmer" that provides intelligent code completion and a chatbot capable of answering any programming-related questions.</p>
<p>The concept behind GitHub Copilot is to enable developers to generate code more quickly, primarily by minimizing the amount of typing needed for boilerplate code and saving time when searching for answers to questions. Instead of using Google to find a solution, you can simply enter your question into the chatbot integrated with your IDE and receive a detailed, customized answer for your program in seconds.</p>
<p>In this review, I will provide my honest feedback on my experience using GitHub Copilot in various contexts, such as learning a new programming language, learning and practicing machine learning in Python, and developing a personal project. I will discuss some of the standout features that I use, identify areas where I believe improvements could be made, and share my overall evaluation of Copilot.</p>
<p>To preface, although this is not a sponsored post, I am able to use Copilot for free as a university student. My access to GitHub's student developer pack, which includes a free Copilot subscription, is granted due to my student status. As a result, my review may be somewhat biased, as the average person would need to pay for a subscription.</p>
<p>In addition to the point above, as a student, my experience with Copilot may be biased because I lack professional experience as a software engineer. Consequently, I cannot attest to how Copilot would perform in a "real-world" setting.</p>
<p>My goal in this review is to offer insights into how Copilot functions, as well as its features and drawbacks, before someone decides to purchase a subscription for its use.</p>
<hr />
<h2 id="heading-the-pros-unveiling-the-strengths">The Pros: Unveiling the Strengths</h2>
<p>GitHub Copilot is an incredibly powerful developer tool that, at times, feels as if you have an additional developer by your side, attentively observing your every move and offering assistance. This unique characteristic can be both a strength and a weakness, depending on the specific situation. In this section, we will focus on the positive aspects and strengths of GitHub Copilot, shedding light on its capabilities and potential benefits for users.</p>
<p>As a cutting-edge AI-powered tool, GitHub Copilot brings a wealth of knowledge and experience to the table, assisting developers in writing code more efficiently and effectively. By providing real-time suggestions and recommendations, it can help streamline the development process, reduce the time spent on repetitive tasks, and even offer insights into best practices and coding standards.</p>
<p>Moreover, GitHub Copilot's ability to learn from a vast repository of code and adapt to individual coding styles makes it a versatile and valuable asset for developers across various skill levels and programming languages. This adaptability allows it to cater to the unique needs and preferences of each user, fostering a more personalized and productive coding experience.</p>
<p>In summary, GitHub Copilot's strengths lie in its powerful AI-driven capabilities, real-time assistance, and adaptability to individual coding styles. These features combine to create a tool that can significantly enhance the development process and help users achieve their goals more efficiently. However, it is essential to consider that this level of assistance can also present challenges in certain situations, which we will explore in the following sections.</p>
<h3 id="heading-efficiency-and-productivity">Efficiency and productivity</h3>
<p><img src="https://images.unsplash.com/photo-1499750310107-5fef28a66643?q=80&amp;w=2070&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a laptop computer sitting on top of a wooden desk" class="image--center mx-auto" /></p>
<p>One of the most appealing features of GitHub Copilot is how little code I sometimes need to type. In very simple scenarios, it can suggest precisely, or almost precisely, what I intended to type. Moreover, the suggestions aren't just brief lines here and there; Copilot's recommendations can span several lines and complete entire functions. Consequently, you naturally spend less time fussing with typing boilerplate code and code that feels rudimentary to type.</p>
<p>For example, I recently embarked on a learning journey through the free lectures hosted on FreeCodeCamp's website, aiming to complete the certification for <a target="_blank" href="https://www.freecodecamp.org/learn/machine-learning-with-python/">"Machine Learning with Python"</a>. Throughout the entire process, I had Copilot as my trusty companion in VSCode. To my amazement, I found myself typing very little code, even when the lectures delved into more complex, code-heavy topics.</p>
<p>Since Copilot is trained on a vast array of code sources available online, I surmise that it may have been exposed to the code featured in these lectures, which also appears on the TensorFlow website. Regardless of whether this was the case, the experience of not having to type out any code and instead being able to concentrate on grasping the underlying concepts of machine learning was truly refreshing.</p>
<p>This was particularly beneficial considering that machine learning code often involves a significant amount of boilerplate code and intricate syntax that even seasoned developers aren't expected to recall by heart. In such scenarios, Copilot truly shines as an invaluable tool, enabling learners and developers to focus on understanding the principles and techniques of machine learning, rather than getting bogged down by the minutiae of code syntax and structure.</p>
<p>Consequently, you feel incredibly productive and efficient as a developer who is in the process of learning something new, since you can complete entire programs while also focusing on understanding the concepts.</p>
<h3 id="heading-accuracy-and-usefulness">Accuracy and usefulness</h3>
<p>As previously mentioned, Copilot not only provides code suggestions at every step of the development process, but it also demonstrates remarkable accuracy in specific contexts.</p>
<p>For example, when I used Copilot while learning machine learning in Python, I was amazed to find that Copilot's code suggestions were accurate down to the finest details, even including the exact URL of the datasets I wanted to use in my programs. This level of accuracy is truly impressive and sets Copilot apart from other tools.</p>
<p><img src="https://images.unsplash.com/photo-1456406644174-8ddd4cd52a06?q=80&amp;w=2048&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a man sitting at a table using a laptop computer" class="image--center mx-auto" /></p>
<p>In my experience, I'd estimate that for basic tasks, Copilot's suggestions are accurate about 99% of the time. This makes Copilot an incredibly valuable resource for developers, especially when compared to traditional methods like Google searches, which don't always yield accurate results quickly. With Copilot, not only is the answer available in real-time, but you can also trust that it's highly likely to be accurate.</p>
<p>This high level of accuracy and real-time assistance can significantly improve a developer's workflow, reducing the time spent searching for solutions and increasing overall productivity. By providing reliable and contextually accurate suggestions, Copilot has the potential to become an indispensable tool for developers of all skill levels.</p>
<h3 id="heading-time-savings">Time savings</h3>
<p><img src="https://images.unsplash.com/photo-1495704907664-81f74a7efd9b?q=80&amp;w=2070&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a close up of a person wearing a watch" class="image--center mx-auto" /></p>
<p>Finally, let's discuss time savings. As suggested by my first point, Copilot saves a considerable amount of time that would otherwise be spent typing boilerplate code or basic code.</p>
<p>However, there's another significant area where Copilot demonstrates its ability to save time: documentation. By providing developers with accurate and contextually relevant suggestions, Copilot can help streamline the process of writing comprehensive documentation for software projects. This not only saves time but also ensures that the documentation is consistent, well-structured, and easy to understand.</p>
<p>Developers often spend a considerable amount of time researching and writing documentation to ensure that their code is easily maintainable and understandable by others. With Copilot's assistance, developers can focus more on the core functionality of their projects, while the AI-powered tool takes care of generating relevant documentation.</p>
<p>For instance, I recently utilized Copilot to rapidly generate documentation for several of my personal projects. I was genuinely impressed by the quality and depth of the content it produced in the README files. The AI-powered tool was able to understand the core functionality of my projects and generate relevant explanations, making it easier for others to comprehend the code and its purpose.</p>
<p>However, it's important to note that Copilot's documentation capabilities, while impressive, are not entirely comprehensive. This means that certain aspects of the projects were left unexplained or not covered in sufficient detail. As a result, developers may still need to invest some time in manually creating or refining documentation to ensure that all critical components and nuances are adequately addressed.</p>
<p>However, for kickstarting documentation, Copilot is a decent tool. I don't know about you, but documentation is typically my least favorite part of the development process, so I'll gladly accept any time savings I can get in this area.</p>
<hr />
<h2 id="heading-the-cons-addressing-the-limitations">The Cons: Addressing the Limitations</h2>
<p>This wouldn't be an honest review if I didn't discuss some of the cons and drawbacks that I personally encountered, and which I believe others may experience as well.</p>
<p>I will discuss 3 major cons, but keep in mind that there are plenty more that I won't be mentioning, which have been previously addressed by others in their commentary.</p>
<p>It's important to acknowledge that AI tools are still quite new, and as a result, they're in their early stages regarding how advanced they are at accomplishing their tasks and goals. I believe that as time goes on and these tools continue to be developed, they will only improve.</p>
<p>I also want to preface by saying that I don't buy into the fear-mongering that tools like Copilot will take the jobs of software engineers and developers. As these tools continue to improve, I believe they will simply be integrated into the workflow for developers, making each developer more capable and productive. Ultimately, the primary goal of these tools is to enhance developer productivity, not to create tools that will replace developers themselves.</p>
<h3 id="heading-ambiguousincorrect-code-suggestions">Ambiguous/incorrect code suggestions</h3>
<p><img src="https://images.unsplash.com/photo-1633613286848-e6f43bbafb8d?q=80&amp;w=2070&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a blue question mark on a pink background" class="image--center mx-auto" /></p>
<p>Now, I understand that this point may appear to contradict one of the advantages I mentioned earlier, where Copilot provides highly accurate suggestions. However, it's crucial to acknowledge that I was referring to relatively simple contexts. In more complex situations, particularly those involving proprietary software or specialized tools utilized by businesses, Copilot's suggestions might not be as impressive or accurate as one would hope.</p>
<p>It's important to remember that AI models like Copilot are trained on vast amounts of publicly available code, which means that their understanding of proprietary or industry-specific tools may be limited. As a result, developers working with such tools may find that Copilot's suggestions are less helpful or even incorrect in certain cases. This is not to say that Copilot is entirely ineffective in these situations, but rather that its effectiveness may be somewhat diminished.</p>
<p>That being said, I cannot definitively confirm whether this is true or not, as I am still a college student without direct experience working in the field. However, it's worth considering this potential limitation when evaluating the usefulness of AI-powered code assistants like Copilot. As these tools continue to evolve and improve, it's possible that their understanding of specialized tools and proprietary software will expand, making them even more valuable for developers across various industries and domains.</p>
<h3 id="heading-cost">Cost</h3>
<p><img src="https://images.unsplash.com/photo-1692598506940-da51e1c42143?q=80&amp;w=1974&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a dollar bill sticking out of the back pocket of a pair of jeans" class="image--center mx-auto" /></p>
<p>This is both a drawback I have yet to experience (since I'm currently able to use Copilot for free as a college student) and a drawback that is not subjective, but simply factual: Copilot costs money.</p>
<p>At the time of writing this article, the cost for Copilot is as follows: $10/month for individuals, $19/user/month for businesses, and $39/user/month for enterprises.</p>
<p>Now, aside from the fact that Copilot would be another monthly subscription that might catch you off guard, you have to ask yourself: "Is it worth the cost for what I do?".</p>
<p>I cannot answer this question, as everyone's situation is unique. However, I will say that if I were a student and had to pay $10/month for Copilot, I wouldn't. In my opinion, unless your company provides Copilot as a complimentary "perk," it's not worth using.</p>
<p>Although Copilot is impressive, there are plenty of free and user-friendly resources available, including both traditional materials and AI tools like ChatGPT.</p>
<p>If Copilot's capabilities significantly surpass the free resources available, then perhaps I would reconsider my stance on paying for it.</p>
<p>That being said, GitHub does offer a free 30-day trial for trying out Copilot. So, if you want to see what all the hype is about for yourself, you can at least do so without any cost.</p>
<h3 id="heading-annoying-while-learning-new-language">Annoying while learning new language</h3>
<p><img src="https://images.unsplash.com/photo-1599687266725-0d4d52716b86?q=80&amp;w=2070&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="a woman sitting on a bench with a laptop" class="image--center mx-auto" /></p>
<p>Unlike the other drawbacks I mentioned, this one I can personally vouch for.</p>
<p>One of the use cases where I've tried Copilot is while learning the C programming language. I quickly realized how much it hindered my learning, so I disabled it in my workspace designated for learning C (which is very easy to do, by the way).</p>
<p>Recall at the beginning of this article when I mentioned that Copilot is like having another developer constantly looking over your shoulder and providing commentary every second? Well, this isn't ideal when trying to learn a new programming language.</p>
<p>When embarking on the journey to learn a new programming language, I found that Copilot transformed from a helpful assistant into an intrusive companion, negatively impacting my ability to concentrate on the learning process. The primary objective of learning a new programming language is to gain a comprehensive understanding of the syntax, enabling efficient navigation and problem-solving within the language. Additionally, it's crucial to develop the skills required to independently create and manage projects using the language. However, with Copilot's constant input and suggestions, it becomes increasingly challenging to achieve these goals.</p>
<p>As a developer trying to learn a new language, it's essential to engage in hands-on practice, trial and error, and problem-solving exercises to build a strong foundation. Copilot's continuous presence and guidance can inadvertently lead to over-reliance on its suggestions, preventing learners from developing their own understanding and intuition. By constantly providing commentary and solutions, Copilot may hinder the growth of critical thinking and problem-solving skills, which are vital for mastering any programming language.</p>
<p>In summary, while Copilot can be a valuable tool for experienced developers working on complex projects, it may not be the ideal companion for those attempting to learn a new programming language. Its constant input can obstruct the learning process, making it difficult for learners to develop the necessary skills and understanding to become proficient in their chosen language.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, GitHub Copilot is a powerful AI-driven tool that offers a wealth of benefits for developers, particularly in terms of efficiency, accuracy, and time savings.</p>
<p>However, it's not without its limitations. The effectiveness of its code suggestions can be compromised in unique scenarios, the cost may be prohibitive for some, and its constant input can be more of a hindrance than a help when learning a new programming language.</p>
<p>As with any tool, its value will largely depend on the specific needs and circumstances of the user. Despite its drawbacks, Copilot's potential to enhance developer productivity is undeniable, and it will be interesting to see how it evolves in the future.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[A Basic Guide to Pointers in C Programming]]></title><description><![CDATA[Introduction

This article provides a comprehensive guide on pointers in the C programming language. It starts by defining pointers and explaining their importance in C programming, such as efficient memory management and low-level memory manipulatio...]]></description><link>https://scrappedscript.com/a-basic-guide-to-pointers-in-c-programming</link><guid isPermaLink="true">https://scrappedscript.com/a-basic-guide-to-pointers-in-c-programming</guid><category><![CDATA[C]]></category><category><![CDATA[pointers]]></category><category><![CDATA[low level programming]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 19 Dec 2023 12:12:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/lYxQ5F9xBDM/upload/d22e44d7c7b64525e932516d9e461341.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>This article provides a comprehensive guide on pointers in the C programming language. It starts by defining pointers and explaining their importance in C programming, such as efficient memory management and low-level memory manipulation. The article then delves into the declaration and initialization of pointers, and how to dereference them to access the value stored at the memory address they point to. It further explores pointer arithmetic for efficient navigation through memory, and the use of pointers in functions to facilitate pass-by-reference behavior. The article concludes by emphasizing the importance of practice and understanding of memory management to effectively use pointers and enhance programming abilities.</p>
</blockquote>
<hr />
<h2 id="heading-what-are-pointers">What are pointers?</h2>
<p>A pointer in C is a specialized type of variable that holds the memory address of another variable. Rather than directly interacting with data, pointers provide programmers with the ability to indirectly access and modify memory locations. This level of indirection is a fundamental concept in C programming that opens the door for a range of powerful and flexible programming techniques.</p>
<p>Pointers are particularly useful in C because they enable efficient memory management and low-level memory manipulation. By utilizing pointers, developers can create dynamic data structures, pass large data sets to functions without duplicating memory, and interact with hardware devices. Furthermore, pointers can be used to implement complex algorithms that require precise control over memory allocation and deallocation.</p>
<p>In essence, pointers act as a bridge between the high-level abstractions of C programming and the underlying hardware. They allow programmers to harness the full power of the computer's memory system, enabling the creation of efficient and dynamic code that can adapt to various situations and requirements. As a result, understanding pointers and their proper usage is essential for any C programmer looking to write optimized and versatile software.</p>
<hr />
<h2 id="heading-how-to-declare-and-initialize-pointers">How to declare and initialize pointers</h2>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> num = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">int</span> *numP;

    numP = &amp;num;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of num: %d\n"</span>, num); <span class="hljs-comment">// 10</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Address of num: %p\n"</span>, &amp;num); <span class="hljs-comment">// address of num in the stack</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of numP: %p\n"</span>, numP); <span class="hljs-comment">// address of num in the stack</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>To declare a pointer in the C programming language, you need to follow a few simple steps. First, you must specify the type of data that the pointer will be pointing to. This is important because it helps the compiler understand how much memory should be allocated for the pointer and how to interpret the data stored at the memory address it points to. In the example provided above, the pointer is intended to point to an integer data type.</p>
<p>Next, you need to use the <code>*</code> syntax, which is a special symbol that indicates you are declaring a pointer variable. This asterisk is placed before the name of the pointer during its declaration, signaling to the compiler that the variable being declared is a pointer.</p>
<p>Finally, you should choose a name for the pointer. While you have the freedom to name the pointer anything you like, it is a common practice to use the same name as the variable it points to, followed by a "p" to indicate that it is a pointer. This naming convention makes it easier for you and others to understand the purpose of the pointer when reading the code.</p>
<p>In the example code provided, an integer variable <code>num</code> is declared and initialized with the value 10. Then, a pointer to an integer, <code>numP</code>, is declared. To initialize the pointer, the address of the <code>num</code> variable is assigned to it using the address-of operator <code>&amp;</code>. This makes <code>numP</code> point to the memory location where the <code>num</code> variable is stored.</p>
<hr />
<h2 id="heading-dereferencing-pointers">Dereferencing pointers</h2>
<p>To dereference a pointer, you need to use the asterisk symbol (*) followed by the pointer's name. This process essentially retrieves the value stored at the memory address that the pointer is pointing to.</p>
<p>For example, in the given context, we have an integer variable <code>num</code> initialized with the value 10 and a pointer to an integer, <code>numP</code>, which is assigned the address of the <code>num</code> variable using the address-of operator (&amp;). By dereferencing the pointer <code>numP</code> using the asterisk symbol, we can access the value stored in the memory location where the <code>num</code> variable is stored. This is done by writing <code>*numP</code> in the code, which would then return the value 10, as that is the value stored at the memory address to which <code>numP</code> is pointing.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> num = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">int</span> *numP = &amp;num;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of num: %d\n"</span>, num); <span class="hljs-comment">// 10</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of num using pointer: %d\n"</span>, *numP); <span class="hljs-comment">// 10</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>I understand that this concept might be confusing (I was also confused when I first learned about pointers in C). Just remember that the asterisk symbol is required for declaring pointer variables. However, when the asterisk symbol is used after the pointer has already been declared, it serves to return the value stored at the memory address to which the pointer is pointing.</p>
<hr />
<h2 id="heading-pointer-arithmetic">Pointer arithmetic</h2>
<p>In C, arithmetic operations on pointers are allowed, providing a powerful mechanism for navigating through memory efficiently. This feature enables developers to perform calculations with pointer variables, which can be particularly useful when working with arrays or other data structures that require direct memory manipulation.</p>
<p>For example, when an integer is added to a pointer, the address stored in the pointer is incremented by a number of bytes corresponding to the integer value. This allows for easy traversal through memory, as the pointer can be moved to the next memory location by simply adding the appropriate value. The size of the increment depends on the data type of the pointer, as different data types occupy different amounts of memory. For instance, if the pointer is of type <code>int</code>, and the size of an <code>int</code> is 4 bytes, adding 1 to the pointer would increment its address by 4 bytes, effectively moving it to the next <code>int</code> value in memory.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> arr[] = {<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>};
    <span class="hljs-keyword">int</span> *ptr = arr; <span class="hljs-comment">// Point to the first element of the array</span>

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Initial value: %d\n"</span>, *ptr);

    ptr++; <span class="hljs-comment">// Increment the pointer to point to next element</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value after incrementing pointer: %d\n"</span>, *ptr);

    ptr--; <span class="hljs-comment">// Decrement the pointer to point to previous element</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value after decrementing pointer: %d\n"</span>, *ptr);

    ptr += <span class="hljs-number">3</span>; <span class="hljs-comment">// Add 3 to the pointer to point to the element 3 spots to the right</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value after adding 3 to pointer: %d\n"</span>, *ptr);

    ptr -= <span class="hljs-number">2</span>; <span class="hljs-comment">// Subtract 2 from the pointer to point to the element 2 spots to the left</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value after subtracting 2 from pointer: %d\n"</span>, *ptr);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In the example provided above, we start by assigning the pointer to point to the first element of the array. This is a crucial step as it establishes a reference point for our pointer to work with. Once we have the pointer pointing to the first element, we can effortlessly employ pointer arithmetic to navigate and manipulate different elements within the array.</p>
<p>By incrementing or decrementing the pointer, we can traverse the array in either direction. This allows us to access and modify the values of the array elements without using the traditional array indexing method. Furthermore, we can add or subtract specific values to the pointer to directly access elements at a certain distance from the current position of the pointer.</p>
<hr />
<h2 id="heading-pointers-and-functions">Pointers and functions</h2>
<p>Pointers are often utilized in C functions to facilitate pass-by-reference behavior, which is a powerful technique that allows functions to directly modify the original values of variables that are located outside their local scope. This is particularly useful in situations where a function needs to alter multiple values or work with large data structures, as it can help to avoid the overhead of copying data and improve the overall efficiency of the program.</p>
<p>For example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">updateValue</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *ptr)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> num = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">int</span> *ptr = &amp;num;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Before update: %d\n"</span>, num); <span class="hljs-comment">// 10</span>
    updateValue(ptr);
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"After update: %d\n"</span>, num); <span class="hljs-comment">// 15</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">updateValue</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *ptr)</span> </span>{
    *ptr = *ptr + <span class="hljs-number">5</span>;
}
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Pointers are a fundamental and crucial aspect of C programming that provides access to powerful capabilities, such as dynamic memory management and efficient data manipulation. They serve as a bridge to understanding and managing memory allocation, which is a key skill for any C programmer. While pointers may initially seem complex and challenging to grasp, mastering them is essential for becoming a proficient and skilled C programmer.</p>
<p>To truly harness the potential of pointers in C, it is important to invest time in practice, exhibit patience, and develop a clear understanding of memory management concepts. As you gain experience working with pointers, you will begin to appreciate their versatility and the numerous advantages they offer in terms of performance optimization and code flexibility.</p>
<p>For example, using pointers allows you to directly manipulate memory addresses, enabling you to pass large data structures to functions more efficiently. This can lead to significant performance improvements, as you no longer need to create copies of large data structures when passing them between functions. Additionally, pointers enable you to allocate and deallocate memory dynamically, which can be particularly useful when working with data structures that change in size during the execution of a program.</p>
<p>In conclusion, pointers are an indispensable tool in the C programming language that offers a range of powerful capabilities. By dedicating time to practice and developing a deep understanding of memory management, you can unlock the true potential of pointers and become a more proficient C programmer. Embrace the challenge of learning pointers, and you will be rewarded with a valuable skill set that can greatly enhance your programming abilities.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Comparing Data Structures: Stacks vs Queues]]></title><description><![CDATA[Introduction

This article provides an in-depth look at two fundamental data structures in programming: stacks and queues. It discusses the characteristics, advantages, and disadvantages of both, with Python code examples provided for better understa...]]></description><link>https://scrappedscript.com/comparing-data-structures-stacks-vs-queues</link><guid isPermaLink="true">https://scrappedscript.com/comparing-data-structures-stacks-vs-queues</guid><category><![CDATA[Python]]></category><category><![CDATA[data structures]]></category><category><![CDATA[queue]]></category><category><![CDATA[stack]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 12 Dec 2023 16:24:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ecUVGNZA1TM/upload/950ea42333532a451475cef0bf4c42ea.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>This article provides an in-depth look at two fundamental data structures in programming: stacks and queues. It discusses the characteristics, advantages, and disadvantages of both, with Python code examples provided for better understanding. Stacks, operating on a Last In First Out (LIFO) principle, are efficient in memory usage and fast in operations, but lack flexibility and search operations. Queues, following the First In First Out (FIFO) model, are predictable and widely used, but can be inefficient in memory usage and slower in operations. The choice between a stack and a queue depends on the specific problem you are trying to solve.</p>
</blockquote>
<hr />
<h2 id="heading-i-stacks">I. Stacks</h2>
<p>Similar to a list, a stack is an ordered sequence of values.</p>
<p>A stack is a linear data structure that follows a particular order in which operations are performed. The order in which values are added to a stack is LIFO (Last In First Out).</p>
<p>In Python, you can create a stack data structure using either an implementation of lists or linked lists.</p>
<p>In this article, I'll be demonstrating how to use Python's built-in list data structure to create a stack data structure.</p>
<h3 id="heading-a-creating-a-stack-in-python">a) Creating a stack in Python</h3>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.items = []

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">push</span>(<span class="hljs-params">self, item</span>):</span>
        self.items.append(item)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pop</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self.is_empty():
            <span class="hljs-keyword">return</span> self.items.pop()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">peek</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self.is_empty():
            <span class="hljs-keyword">return</span> self.items[<span class="hljs-number">-1</span>]

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_empty</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> len(self.items) == <span class="hljs-number">0</span>

<span class="hljs-comment"># Example usage:</span>
stack = Stack()
stack.push(<span class="hljs-number">1</span>)
stack.push(<span class="hljs-number">2</span>)
stack.push(<span class="hljs-number">3</span>)
print(stack.pop())  <span class="hljs-comment"># Output: 3</span>
print(stack.peek())  <span class="hljs-comment"># Output: 2</span>
print(stack.is_empty())  <span class="hljs-comment"># Output: False</span>
</code></pre>
<h3 id="heading-b-stack-methods">b) Stack methods</h3>
<p>Some basic methods for stacks include:</p>
<ul>
<li><p>push - adds a value to the top of the stack</p>
</li>
<li><p>pop - removes the value at the top of the stack</p>
</li>
<li><p>peek - returns the value at the top of the stack</p>
</li>
<li><p>is_empty - returns True if the stack is empty, otherwise returns False</p>
</li>
</ul>
<h3 id="heading-c-advantages">c) Advantages</h3>
<p>Some advantages of stacks include:</p>
<ol>
<li><p>Efficient Memory Usage: stacks use a block of memory that fits exactly the amount of data stored, minimizing wasted space.</p>
</li>
<li><p>Fast Operations: All operations like push, pop, and peek have a time complexity of O(1)</p>
</li>
</ol>
<h3 id="heading-d-disadvantages">d) Disadvantages</h3>
<p>Some disadvantages of stacks include:</p>
<ol>
<li><p>Limited Flexibility: Stacks operate on the LIFO principle, which means the most recently added item is the first one to be removed. This lack of flexibility can be a disadvantage in scenarios where access to other values is needed</p>
</li>
<li><p>Lack of Search Operation: Stacks do not allow you to search through the data. To access data that is not on the top of the stack, you must remove its preceding items.</p>
</li>
</ol>
<hr />
<h2 id="heading-ii-queues">II. Queues</h2>
<p>Similar to stacks, a queue is a type of data structure that stores elements in a sequence.</p>
<p>Contrary to stacks, queue operations occur in a FIFO (First In First Out) manner. This means that the element that is inserted first is the one that gets removed first.</p>
<p>Similar to stacks, queues can be implemented using lists or linked lists.</p>
<p>Just like the stacks example, I'm going to demonstrate how you can create queues in Python using an implementation of Python's built-in list data structure.</p>
<h3 id="heading-a-creating-a-queue-in-python">a) Creating a queue in Python</h3>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>        
    self.list = []   

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">enqueue</span>(<span class="hljs-params">self, data</span>):</span>        
    self.list.append(data)    

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dequeue</span>(<span class="hljs-params">self</span>):</span>        
    val = self.list[<span class="hljs-number">0</span>]        
    <span class="hljs-keyword">del</span> self.list[<span class="hljs-number">0</span>]        
    <span class="hljs-keyword">return</span> val    

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_empty</span>(<span class="hljs-params">self</span>):</span>        
    <span class="hljs-keyword">return</span> len(self.list) == <span class="hljs-number">0</span>

<span class="hljs-comment"># Example usage:</span>
my_queue = Queue()
my_queue.enqueue(<span class="hljs-number">1</span>)
my_queue.enqueue(<span class="hljs-number">2</span>)
my_queue.enqueue(<span class="hljs-number">3</span>)
print(my_queue.dequeue())  <span class="hljs-comment"># Output: 1</span>
</code></pre>
<h3 id="heading-b-queue-methods">b) Queue methods</h3>
<p>Some basic methods for queues include:</p>
<ul>
<li><p>enqueue - adds a value to the end of the queue</p>
</li>
<li><p>dequeue - removes the value at the beginning of the queue</p>
</li>
<li><p>is_empty - returns True if the queue is empty, otherwise returns False</p>
</li>
</ul>
<h3 id="heading-c-advantages-1">c) Advantages</h3>
<p>Some advantages of queues include:</p>
<ol>
<li><p>Predictability: Since queues follow the FIFO model, the timing of operations is highly predictable. You always know which item is next in line.</p>
</li>
<li><p>Broad Usage: Queues are used in a wide variety of programming scenarios, such as managing processes in a job scheduling system, handling requests on a single shared resource like a printer, and in CPU scheduling and disk scheduling.</p>
</li>
</ol>
<h3 id="heading-d-disadvantages-1">d) Disadvantages</h3>
<ol>
<li><p>Inefficient Memory Usage: Unlike arrays, queues that are implemented using linked lists can use more memory because of the extra storage needed for pointers.</p>
</li>
<li><p>Slow Operations: Depending on the implementation, operations like enqueue and dequeue can be slower in queues than in arrays or stacks.</p>
</li>
<li><p>Complexity: Queues are more complex to manage than stacks because you need to maintain two pointers (front and rear), compared to stacks where only one pointer (top) is required.</p>
</li>
<li><p>Limited Access: Similar to stacks, queues don't provide the ability to access elements in the middle. You can only directly access the first and last elements.</p>
</li>
</ol>
<hr />
<h2 id="heading-iii-conclusion">III. Conclusion</h2>
<p>In conclusion, both stacks and queues are essential data structures in programming, each with their unique characteristics and use cases.</p>
<p>Stacks operate on the LIFO principle, making them ideal for scenarios that require reversing or where the most recent data is of primary interest. On the other hand, queues operate on the FIFO model, making them suitable for maintaining the order of operations and handling asynchronous tasks.</p>
<p>However, both have their limitations. Stacks lack flexibility and do not support search operations, while queues can be inefficient in memory usage and slower in operations. Therefore, the choice between a stack and a queue depends on the specific requirements of the problem you are trying to solve.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Utilizing Keras to Augment Images]]></title><description><![CDATA[Introduction

In this article, we discuss how to install Keras and Skimage, and demonstrate the process of image augmentation using the ImageDataGenerator object from Keras. Image augmentation is useful for creating larger training datasets for objec...]]></description><link>https://scrappedscript.com/utilizing-keras-to-augment-images</link><guid isPermaLink="true">https://scrappedscript.com/utilizing-keras-to-augment-images</guid><category><![CDATA[Python]]></category><category><![CDATA[keras]]></category><category><![CDATA[image processing]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 28 Nov 2023 16:34:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ZIPFteu-R8k/upload/291bb5fb85490086bdc6def461d4899a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>In this article, we discuss how to install Keras and Skimage, and demonstrate the process of image augmentation using the ImageDataGenerator object from Keras. Image augmentation is useful for creating larger training datasets for object recognition models, such as HOG or CNN, by artificially generating new images based on the original ones. We provide step-by-step instructions for installing the required libraries, loading and reshaping images, and finally, generating augmented images.</p>
</blockquote>
<hr />
<h2 id="heading-how-to-install-keras">How to install Keras</h2>
<p>To install Keras, you have to install the TensorFlow package.</p>
<p>To install TensorFlow:</p>
<pre><code class="lang-bash">pip install tensorflow
</code></pre>
<p>After installing the TensorFlow package, you've now installed Keras onto your system.</p>
<p>To use Keras in your Python file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> tensorflow <span class="hljs-keyword">import</span> keras
</code></pre>
<hr />
<h2 id="heading-how-to-install-skimage">How to install Skimage</h2>
<p>To load in our image, we'll be using SciKit, but you may wish to use another library to load in your image if you'd prefer.</p>
<p>To install Skimage:</p>
<pre><code class="lang-bash">pip install scikit-image
</code></pre>
<hr />
<h2 id="heading-image-augmentation">Image augmentation</h2>
<p>To start, make sure to import the required modules into your Python file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> keras.preprocessing.image <span class="hljs-keyword">import</span> ImageDataGenerator
<span class="hljs-keyword">from</span> skimage <span class="hljs-keyword">import</span> io
</code></pre>
<h3 id="heading-imagedatagenerator-object">ImageDataGenerator object</h3>
<p>The next step is to use the ImageDataGenerator object from Keras to define how you want the augmented image(s) to be transformed:</p>
<pre><code class="lang-python">datagen = ImageDataGenerator(
    rotation_range=<span class="hljs-number">40</span>,  <span class="hljs-comment"># randomly rotate images in the range (degrees, 0 to 180)</span>
    width_shift_range=<span class="hljs-number">0.2</span>,  <span class="hljs-comment"># randomly shift images horizontally (fraction of total width)</span>
    height_shift_range=<span class="hljs-number">0.2</span>,  <span class="hljs-comment"># randomly shift images vertically (fraction of total height)</span>
    shear_range=<span class="hljs-number">0.2</span>,  <span class="hljs-comment"># set range for random shear</span>
    zoom_range=<span class="hljs-number">0.2</span>,  <span class="hljs-comment"># set range for random zoom</span>
    horizontal_flip=<span class="hljs-literal">True</span>,  <span class="hljs-comment"># randomly flip images</span>
    fill_mode=<span class="hljs-string">'nearest'</span>)  <span class="hljs-comment"># set mode for filling points outside the input boundaries</span>
</code></pre>
<p>When you set 'fill_mode' to 'nearest', any space created in the augmented images will be filled with colored pixels that match the colors of the pixels near the space.</p>
<p>Another option for 'fill_mode' is to set it to 'constant'. When you set it to constant, the space in the augmented images will be filled with black pixels by default. If you want to use grey or white pixels, you can do so by including a 2nd argument after 'fill_mode', like so: "fill_mode='nearest', '150'".</p>
<h3 id="heading-load-image-and-reshape">Load image and reshape</h3>
<p>In this step, you'll load your image into Python. Additionally, we'll be reshaping the image array data.</p>
<pre><code class="lang-python">input_image = io.imread(<span class="hljs-string">'path/to/image'</span>)
input_image = input_image.reshape((<span class="hljs-number">1</span>,) + input_image.shape)
</code></pre>
<h3 id="heading-generate-x-augmented-images">Generate <em>x</em> augmented images</h3>
<p>The final step is to generate your augmented images!</p>
<p>The following code demonstrates creating and saving 20 augmented images:</p>
<pre><code class="lang-python">i = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> datagen.flow(input_image, batch_size=<span class="hljs-number">16</span>, save_to_dir=<span class="hljs-string">'path/to/save/images'</span>, save_prefix=<span class="hljs-string">'prefix'</span>, save_format=<span class="hljs-string">'jpeg'</span>):
        i += <span class="hljs-number">1</span>
        <span class="hljs-keyword">if</span> i == <span class="hljs-number">19</span>:
            <span class="hljs-keyword">break</span>
</code></pre>
<p>In the above code, we're calling the .flow function on our ImageDataGenerator object and passing in our input_image, a batch size of 16 (this means it will augment 16 sample images at a time), specifying the directory to save the augmented images, specifying the prefix to put at the beginning of all the file names, and finally, the file format of the augmented images.</p>
<hr />
<h2 id="heading-whats-the-benefit-of-image-augmentation">What's the benefit of image augmentation?</h2>
<p>If you're trying to train a histogram of oriented gradients (HOG) model or a convolutional neural network (CNN) model to do any type of object recognition, then image augmentation may be of use to you.</p>
<p>In particular, if you don't have a large enough training dataset of images, then you can artificially create a large dataset of training images by augmenting the original images that you already have.</p>
<p>By creating this image augmentation pipeline, your model will train not only on the original images contained in your training dataset but also all of the augmented images that are generated based on those original images.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Comparing Data Structures: Lists vs Linked Lists]]></title><description><![CDATA[Introduction

In this article, we explore the similarities and differences between lists and linked lists, two common data structures in programming.
We discuss their characteristics, advantages, and disadvantages, as well as how to create and manipu...]]></description><link>https://scrappedscript.com/comparing-data-structures-lists-vs-linked-lists</link><guid isPermaLink="true">https://scrappedscript.com/comparing-data-structures-lists-vs-linked-lists</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Python]]></category><category><![CDATA[data structures]]></category><category><![CDATA[linked list]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 21 Nov 2023 16:51:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BW0vK-FA3eg/upload/908ca908b79a4463343f88adf6155d3e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>In this article, we explore the similarities and differences between lists and linked lists, two common data structures in programming.</p>
<p>We discuss their characteristics, advantages, and disadvantages, as well as how to create and manipulate them in Python. By understanding the strengths and weaknesses of each data structure, you can make informed decisions on which to use for your specific tasks.</p>
</blockquote>
<hr />
<h2 id="heading-i-lists">I. Lists</h2>
<p>Lists consist of ordered, mutable elements. They enable simple insertion, deletion, and traversal of elements while offering dynamic resizing capabilities.</p>
<p>With lists, all elements are stored contiguously in memory. This characteristic enables lists to quickly return elements at a specified index.</p>
<p>In many programming languages, lists are a built-in data structure. This means that you don't have to manually create lists and their associated methods.</p>
<h3 id="heading-a-creating-a-list-in-python">a) Creating a list in Python</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Creating an empty list</span>
new_list = []

<span class="hljs-comment"># Creating list with values</span>
names = [<span class="hljs-string">'Jack'</span>, <span class="hljs-string">'Jill'</span>, <span class="hljs-string">'Jane'</span>, <span class="hljs-string">'Jeff'</span>]

<span class="hljs-comment"># Creating list with 'list' function</span>
<span class="hljs-comment"># (Python requires iterable argument)</span>
digits_set = {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>}
digits_list = list(digits)
</code></pre>
<p>In the final example of creating a list in Python, we needed to provide an iterable data type, such as a tuple, string, set, or dictionary.</p>
<p>Python converts the iterable data type into a list.</p>
<p>For tuples and sets, this simply means that Python converts all the elements directly into a list while maintaining the same order.</p>
<p>For strings, Python slices the string into individual characters and creates a list element for each character in the string.</p>
<p>For dictionaries, Python creates a list element for each key in the dictionary.</p>
<h3 id="heading-b-list-methods">b) List methods</h3>
<ul>
<li><p>append(<em>el</em>) - adds <em>el</em> to the end of the list</p>
</li>
<li><p>insert(<em>index</em>, <em>el</em>) - adds <em>el</em> to specified <em>index</em> (shifts the elements to the right by 1 index)</p>
</li>
<li><p>remove(<em>el</em>) - removes the first instance of <em>el</em> in the list</p>
</li>
<li><p>pop() - removes the last element of the list, and returns the element it removed</p>
</li>
<li><p>clear() - deletes all the elements from the list</p>
</li>
<li><p>index(<em>index</em>) - returns element at the specified <em>index</em> (this can also be done with square bracket syntax: <code>l[index]</code>)</p>
</li>
<li><p>count(<em>value</em>) - returns the number of elements that contain the value <em>value</em></p>
</li>
<li><p>sort() - sorts the list from least to greatest (or alphabetically for a list of strings)</p>
</li>
<li><p>reverse() - sorts the list from greatest to least (or reverse alphabetically for a list of strings)</p>
</li>
</ul>
<h3 id="heading-c-advantages">c) Advantages</h3>
<p>The primary advantage of lists lies in their simplicity and the fact that they come pre-built in most programming languages.</p>
<p>Secondly, lists provide quick access to elements at a specified index, as they are stored contiguously in memory.</p>
<p>This means that the time complexity of indexing an element in a list is constant:</p>
<p>$$O(1)$$</p><h3 id="heading-d-disadvantages">d) Disadvantages</h3>
<p>The primary drawback of lists is that they are somewhat slow when it comes to removing and inserting elements at specific indices.</p>
<p>This is due to the necessity of shifting all elements to maintain contiguity in memory, which results in slower insertion and removal of elements at specific indices.</p>
<p>This means that the time complexity for removing and inserting elements in a list is linear:</p>
<p>$$O(n)$$</p><h2 id="heading-ii-linked-lists">II. Linked lists</h2>
<p>Linked lists are a data structure composed of nodes, with each node containing an element and a reference to the subsequent node in the sequence. This enables efficient insertion and deletion of elements at any position but demands more memory and offers slower element access compared to lists.</p>
<p>Unlike lists, linked lists are not built-in data structures, which means you will need to manually code and create linked lists along with their associated methods.</p>
<h3 id="heading-a-creating-a-linked-list">a) Creating a linked list</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Class to construct new nodes</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, data</span>):</span>
        self.data = data
        self.next = <span class="hljs-literal">None</span>

<span class="hljs-comment"># Class to construct new linked lists</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LinkedList</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.head = <span class="hljs-literal">None</span>

    <span class="hljs-comment"># Method to add new nodes to linked list</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">append</span>(<span class="hljs-params">self, data</span>):</span>
        <span class="hljs-comment"># If linked list is empty</span>
        <span class="hljs-keyword">if</span> self.head <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
            self.head = Node(data)
            <span class="hljs-keyword">return</span>

        last_node = self.head
        <span class="hljs-keyword">while</span> last_node.next <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            last_node = last_node.next
        last_node.next = Node(data)

<span class="hljs-comment"># Example usage:</span>
linked_list = LinkedList()
linked_list.append(<span class="hljs-number">1</span>)
linked_list.append(<span class="hljs-number">2</span>)
linked_list.append(<span class="hljs-number">3</span>)
</code></pre>
<h3 id="heading-b-linked-list-methods">b) Linked list methods</h3>
<p>All the methods you've seen for lists can be adapted for linked lists; however, you'll need to manually code each method yourself.</p>
<h3 id="heading-c-advantages-1">c) Advantages</h3>
<p>The primary benefit of linked lists lies in their efficiency when it comes to inserting and removing nodes.</p>
<p>Since nodes are not stored contiguously in memory but are instead referenced or pointed to by the previous node, this allows for constant-time insertion and removal of nodes.</p>
<p>Thus, the time complexity for inserting and removing nodes in linked lists is:</p>
<p>$$O(1)$$</p><h3 id="heading-d-disadvantages-1">d) Disadvantages</h3>
<p>The primary drawback of linked lists is retrieving the value of a node at a specific index.</p>
<p>Since the nodes are not stored contiguously in memory, it means that to retrieve a node at a specific index, we must start at the first node and continue iterating through the linked list until we find the desired node.</p>
<p>Thus, the time complexity for retrieving a node at a specific index is linear:</p>
<p>$$O(n)$$</p><p>If you wish to learn more about the linear search algorithm, I have written a comprehensive article comparing and contrasting linear search and binary search algorithms: <a target="_blank" href="https://scrappedscript.com/comparing-search-algorithms-linear-search-vs-binary-search">Comparing Search Algorithms: Linear Search vs Binary Search.</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://scrappedscript.com/comparing-search-algorithms-linear-search-vs-binary-search">https://scrappedscript.com/comparing-search-algorithms-linear-search-vs-binary-search</a></div>
<p> </p>
<p>In the article, I discuss the reasons why binary search is faster than linear search.</p>
<p>After reading the article, please leave a comment below with your answer to the question: <em>Can we use the binary search algorithm for a linked list?</em></p>
<h2 id="heading-iii-conclusion">III. Conclusion</h2>
<p>I hope that you now understand the similarities and differences between lists and linked lists.</p>
<p>Both lists and linked lists have their own set of advantages and disadvantages.</p>
<p>This means that it's important to consider the task(s) you want to solve before choosing whether you want to implement a list or linked list.</p>
<p>If you want to primarily be able to index elements, then a list may be the better option. On the other hand, if you want to primarily be able to insert and remove values from specific indices, then a linked list is the better option.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Comparing Sorting Algorithms: Bubble Sort vs Insertion Sort]]></title><description><![CDATA[Introduction
In this article, we will delve into two basic sorting algorithms: Bubble Sort and Insertion Sort. We will explore their steps, implementation in Python code, time complexity, advantages, and disadvantages, providing you with a comprehens...]]></description><link>https://scrappedscript.com/comparing-sorting-algorithms-bubble-sort-vs-insertion-sort</link><guid isPermaLink="true">https://scrappedscript.com/comparing-sorting-algorithms-bubble-sort-vs-insertion-sort</guid><category><![CDATA[algorithms]]></category><category><![CDATA[sorting algorithms]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 14 Nov 2023 19:14:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xrVDYZRGdw4/upload/b30f311a1d21c12a32f48c97262ef037.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In this article, we will delve into two basic sorting algorithms: Bubble Sort and Insertion Sort. We will explore their steps, implementation in Python code, time complexity, advantages, and disadvantages, providing you with a comprehensive understanding of these fundamental sorting techniques.</p>
<p>Whether you're a beginner in computer science or a seasoned programmer, this comparison will sharpen your knowledge and help you make informed decisions when choosing the right sorting algorithm for your projects.</p>
<hr />
<h2 id="heading-bubble-sort">Bubble Sort</h2>
<p>Bubble sort works by comparing two values at a time and sorting those two values as it iterates through the entire list.</p>
<p>You can think of it as if it's creating a bubble of the list every time it compares two consecutive values.</p>
<p>The bubble sort algorithm passes through the list n - 1 times and iterates through 1 less element each iteration.</p>
<p>Just from the description, you may already tell that the bubble sort algorithm is not an efficient sorting algorithm.</p>
<p>However, bubble sort is a good algorithm for beginner software engineers to study and understand so that they grasp the foundational concepts of algorithms in general.</p>
<h3 id="heading-algorithm-steps">Algorithm Steps</h3>
<ol>
<li><p>Start at the first two elements in the list</p>
</li>
<li><p>Compare those elements</p>
</li>
<li><p>Swap those elements if they're not sorted</p>
</li>
<li><p>Move to the next two elements and repeat steps 2 and 3</p>
</li>
<li><p>Repeat steps 1-4 till you reach the end of the list</p>
</li>
<li><p>Repeat steps 1-5 till the list is sorted</p>
</li>
</ol>
<h3 id="heading-code-snippet">Code Snippet</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bubble_sort</span>(<span class="hljs-params">arr</span>):</span>

    <span class="hljs-comment"># Iterate through list (n - 1) times</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(arr) - <span class="hljs-number">1</span>):

        <span class="hljs-comment"># Iterate through entire list first time</span>
        <span class="hljs-comment"># Subsequently chop last element from iteration</span>
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(len(arr) - i - <span class="hljs-number">1</span>):

            <span class="hljs-comment"># If the element before the other element is greater,</span>
            <span class="hljs-comment"># swap their order</span>
            <span class="hljs-keyword">if</span> arr[j] &gt; arr[j + <span class="hljs-number">1</span>]:

                arr[j], arr[j + <span class="hljs-number">1</span>] = arr[j + <span class="hljs-number">1</span>], arr[j]

<span class="hljs-comment"># Example Usage:</span>
arr = [<span class="hljs-number">64</span>, <span class="hljs-number">34</span>, <span class="hljs-number">25</span>, <span class="hljs-number">12</span>, <span class="hljs-number">22</span>, <span class="hljs-number">11</span>, <span class="hljs-number">90</span>]
bubble_sort(arr)
</code></pre>
<h3 id="heading-time-complexity">Time complexity</h3>
<p>Regardless of whether the list is partially sorted, or even fully sorted, bubble sort is a very slow algorithm.</p>
<p>This is because no matter what, you iterate through the list n - 1 times, and make 2 comparisons for each element included in each iteration.</p>
<p>This means that the bubble sort time complexity is</p>
<p>$$O(n^2)$$</p><p>This means that we need to make n^2 comparisons for a list of length n.</p>
<p>Bubble sort time complexity graph:</p>
<iframe src="https://www.desmos.com/calculator/eoteinxlt4?embed" width="500" height="500" style="border:1px solid #ccc"></iframe>

<h3 id="heading-advantages">Advantages</h3>
<p>The main advantage of bubble sort is that it's very simple for beginner software engineers to conceptually understand and implement into code.</p>
<h3 id="heading-disadvantages">Disadvantages</h3>
<p>The biggest and most apparent of bubble sort is the incredible inefficiency.</p>
<p>Since the bubble sort time complexity is so large, it's rarely used in practice.</p>
<hr />
<h2 id="heading-insertion-sort">Insertion Sort</h2>
<p>Insertion sort is another slow sorting algorithm but is <em>usually</em> faster than bubble sort.</p>
<p>Again, even though this algorithm is slow, it's a good algorithm to study as a beginner software engineer.</p>
<p>Insertion sort works by dividing the list into a sorted and an unsorted section. It iterates through the unsorted section, taking one element at a time and inserting it into its correct position in the sorted section. This process continues until all elements from the unsorted section have been inserted into the sorted section in the correct order.</p>
<h3 id="heading-algorithm-steps-1">Algorithm Steps</h3>
<ol>
<li><p>Start by pulling the second element in the list</p>
</li>
<li><p>Look at all the numbers to the left of the vacant spot and slide over all the values larger than the element we pulled out</p>
</li>
<li><p>Insert the element we pulled out into whatever spot is now vacant</p>
</li>
<li><p>Pull the next element out of the list</p>
</li>
<li><p>Repeat steps 2 and 3</p>
</li>
<li><p>Repeat step 4 until the entire list is sorted</p>
</li>
</ol>
<h3 id="heading-code-snippet-1">Code snippet</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">insertion_sort</span>(<span class="hljs-params">arr</span>):</span>

    <span class="hljs-comment"># Iterate through list starting at second element</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, len(arr)):

        key = arr[i]
        j = i - <span class="hljs-number">1</span>

        <span class="hljs-comment"># While the next element index is valid and</span>
        <span class="hljs-comment"># the current element is less than the next element</span>
        <span class="hljs-comment"># being compared</span>
        <span class="hljs-keyword">while</span> j &gt;= <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> key &lt; arr[j]:

            <span class="hljs-comment"># The proceeding element will become the next element</span>
            arr[j + <span class="hljs-number">1</span>] = arr[j]
            j -= <span class="hljs-number">1</span>

        arr[j + <span class="hljs-number">1</span>] = key

<span class="hljs-comment"># Example usage:</span>
arr = [<span class="hljs-number">12</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
insertion_sort(arr)
</code></pre>
<h3 id="heading-time-complexity-1">Time complexity</h3>
<p>The worst-case scenario for insertion sort is if the list starts in the complete reverse order.</p>
<p>In this worst-case scenario, the insertion sort algorithm makes this amount of comparisons:</p>
<p>$$\frac{1}{2} (n^2-n)$$</p><p>Therefore, the insertion sort time complexity is:</p>
<p>$$O(n^2)$$</p><p>If you notice, the insertion sort's time complexity is the same as the bubble sort's time complexity.</p>
<p>However, if a list is partially sorted (meaning some values are already in their correct index), then insertion sort takes less time than bubble sort.</p>
<p>The best case scenario for insertion sort is if the list is already sorted. If the list is already sorted, then insertion sort makes 0 list comparisons. On the other hand, bubble sort's time complexity will remain n^2 even for a fully sorted list.</p>
<p>Therefore, in practice, the insertion sort algorithm is usually much faster than the bubble sort algorithm since insertion sort will typically make fewer comparisons than bubble sort.</p>
<h3 id="heading-advantages-1">Advantages</h3>
<p>The biggest advantage of insertion sort is that it's typically faster than the bubble sort algorithm, and the amount of comparisons it makes is dependent on how sorted the list already is. Whereas, bubble sort's time complexity is independent of how sorted the list already is.</p>
<h3 id="heading-disadvantages-1">Disadvantages</h3>
<p>The main disadvantage of insertion sort is that it's still considered a pretty slow sorting algorithm.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope after reading this article, you now have a clearer understanding of the bubble sort and insertion sort algorithms and a more general understanding of the importance of studying algorithms in computer science.</p>
<p>In this article, you learned about the basic concept behind both the bubble sort and insertion sort algorithms, their steps, their implementation in Python code, their time complexity, and some of the advantages and disadvantages for both.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Comparing Search Algorithms: Linear Search vs Binary Search]]></title><description><![CDATA[Introduction
In this article, I'm going to explain how the linear search and binary search algorithms work. In particular, I'm going to review how these algorithms operate as a general list of steps when applied to the context of searching for an ele...]]></description><link>https://scrappedscript.com/comparing-search-algorithms-linear-search-vs-binary-search</link><guid isPermaLink="true">https://scrappedscript.com/comparing-search-algorithms-linear-search-vs-binary-search</guid><category><![CDATA[Python]]></category><category><![CDATA[linearsearch]]></category><category><![CDATA[Binary Search Algorithm]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 07 Nov 2023 21:05:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uv5_bsypFUM/upload/9a76e3e4c4a68d19e4ee2dd1c54b86f7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In this article, I'm going to explain how the linear search and binary search algorithms work. In particular, I'm going to review how these algorithms operate as a general list of steps when applied to the context of searching for an element of a sorted list.</p>
<p>In addition, I'll be including Python code snippets for you to follow along and practice implementing these search algorithms in code.</p>
<p>Lastly, I'll briefly give an overview of the time complexity for both of these search algorithms and go over some advantages and disadvantages for each.</p>
<hr />
<h2 id="heading-i-linear-search">I. Linear search</h2>
<h3 id="heading-a-algorithm-steps">a) Algorithm steps</h3>
<p>Linear search is a very easy algorithm to implement. If you're a beginner programmer, then chances are, you've probably already implemented this algorithm without even realizing it.</p>
<p>The linear search algorithm works as follows:</p>
<ol>
<li><p>Start at the first element in the list and compare its value to the target value</p>
</li>
<li><p>If they're equal, the algorithm is complete</p>
</li>
<li><p>If they're not equal, repeat step 1 with the next element in the list</p>
</li>
<li><p>If you've searched through the whole list and haven't found the target value, you know that the target value isn't in the list</p>
</li>
</ol>
<h3 id="heading-b-code-snippet">b) Code snippet</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_search</span>(<span class="hljs-params">array, target</span>):</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(array)):
        <span class="hljs-keyword">if</span> array[i] == target:
            <span class="hljs-keyword">return</span> i

    <span class="hljs-comment"># If the element isn't found, function will return -1</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>
</code></pre>
<h3 id="heading-c-time-complexity">c) Time complexity</h3>
<p>The worst case for linear search is if the target value isn't in the list OR the target value is the last element of the list.</p>
<p>In this case, we'd have to compare each element in the list to the target value, meaning that we'd make <em>n</em> comparisons.</p>
<p>Therefore the time complexity of linear search is:</p>
<p>$$O(n)$$</p><p>Time complexity graph:</p>
<iframe src="https://www.desmos.com/calculator/b9eokg3rat?embed" width="800" height="500" style="border:1px solid"></iframe>

<h3 id="heading-d-advantages">d) Advantages</h3>
<p>The main advantage of linear search is that this algorithm can be applied to both sorted and unsorted lists.</p>
<h3 id="heading-e-disadvantages">e) Disadvantages</h3>
<p>Of course, the biggest disadvantage of linear search is that it can be very slow and inefficient as a search algorithm.</p>
<hr />
<h2 id="heading-ii-binary-search">II. Binary search</h2>
<h3 id="heading-a-algorithm-steps-1">a) Algorithm steps</h3>
<p>Binary search is easy to understand, but a little harder to implement than linear search.</p>
<p>Keep in mind that the binary search algorithm assumes that the list you're searching is already sorted from least to greatest (or sorted alphabetically from a-z if you have a list of strings).</p>
<p>The binary search algorithm works as follows:</p>
<ol>
<li><p>Start at the middle element in the list and compare its value to the target value</p>
</li>
<li><p>If they're equal, the algorithm is complete</p>
</li>
<li><p>If the target value is greater than the middle element, then re-search the list starting with the element indexed right above the middle element</p>
</li>
<li><p>If the target value is less than the middle element, then re-search the list ending with the element indexed right below the middle element</p>
</li>
<li><p>Repeat until the target element is found</p>
</li>
<li><p>If the target value is not in the spot in the list that it should be, then you know that the target value is not in the list</p>
</li>
</ol>
<h3 id="heading-b-code-snippet-1">b) Code snippet</h3>
<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">array, target</span>):</span>
    low = <span class="hljs-number">0</span> 
    high = len(array) - <span class="hljs-number">1</span>

    <span class="hljs-keyword">while</span> low &lt;= high:
        mid = (low + high) // <span class="hljs-number">2</span>

        <span class="hljs-keyword">if</span> array[mid] == target:
            <span class="hljs-keyword">return</span> mid

        <span class="hljs-keyword">elif</span> array[mid] &gt; target:
            <span class="hljs-comment"># If our target is below the middle value,</span>
            <span class="hljs-comment"># we'll shift the high point right below the middle</span>
            <span class="hljs-comment"># so our search space decreases to the bottom half of</span>
            <span class="hljs-comment"># the list on the next iteration</span>
            high = mid - <span class="hljs-number">1</span>

        <span class="hljs-keyword">else</span>:
            <span class="hljs-comment"># If our target is above the middle value,</span>
            <span class="hljs-comment"># we'll shift the low point right above the middle</span>
            <span class="hljs-comment"># so our search space decreases to the top half of</span>
            <span class="hljs-comment"># the list on the next iteration</span>
            low = mid + <span class="hljs-number">1</span>

    <span class="hljs-comment"># If the target isn't found, the function will return -1</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>
</code></pre>
<h3 id="heading-c-time-complexity-1">c) Time complexity</h3>
<p>The worst case for binary search is if the element isn't in the list (similar to linear search).</p>
<p>For binary search though, since we're halving the search space each iteration, we don't have to search through every element in the list to know that the element isn't in the list.</p>
<p>The most comparisons we have to do to find out that an element isn't in the list is:</p>
<p>$$log_2{n}$$</p><p>Therefore, the time complexity of binary search is:</p>
<p>$$O(log {n})$$</p><p>Time complexity graph:</p>
<iframe src="https://www.desmos.com/calculator/drwmtfwfbh?embed" width="800" height="500" style="border:1px solid #ccc"></iframe>

<p>As you may remember from calculus, logarithm functions increase very slowly. Additionally, the logarithm of a variable will always be less than the variable itself.</p>
<p>$$log(x) &lt; x$$</p><p>This means that for any size list, binary search will always be faster than linear search.</p>
<h3 id="heading-d-advantages-1">d) Advantages</h3>
<p>The main advantage of binary search is obviously that it's always faster than linear search, and is considerably faster for very large lists.</p>
<h3 id="heading-e-disadvantages-1">e) Disadvantages</h3>
<p>The biggest disadvantage of binary search is that it only works for lists that are already sorted.</p>
<p>This means that you'll need to apply a primary sorting algorithm to your list before applying the binary search algorithm for searching for elements from that list.</p>
<hr />
<h2 id="heading-iii-conclusion">III. Conclusion</h2>
<p>I hope that after reading this article, you now have a deeper understanding of the linear search and binary search algorithms.</p>
<p>In this article, you learned the basic steps behind both the linear search and binary search algorithms, you followed along with example Python code snippets for both algorithms and got to see the time complexity for both algorithms.</p>
<p>If you have any lingering questions or suggestions for an article you want me to cover in the future, feel free to leave a comment in the comment section below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content! When you subscribe to my newsletter, you'll be able to read my articles straight from your inbox as soon as they're released.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
]]></content:encoded></item><item><title><![CDATA[Learn the Basics of Python Programming: Control Flow]]></title><description><![CDATA[Introduction

In this article, we explore the concept of control flow in Python, which determines the order of a program's instructions execution. We discuss conditional statements (if, elif, and else), loops (for and while), and loop control stateme...]]></description><link>https://scrappedscript.com/learn-the-basics-of-python-programming-control-flow</link><guid isPermaLink="true">https://scrappedscript.com/learn-the-basics-of-python-programming-control-flow</guid><category><![CDATA[Python]]></category><category><![CDATA[control flow]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 24 Oct 2023 18:44:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/mfxTRWrjtV0/upload/fab297742918565d57b03cf4e2e5ac3e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<blockquote>
<p>In this article, we explore the concept of control flow in Python, which determines the order of a program's instructions execution. We discuss conditional statements (if, elif, and else), loops (for and while), and loop control statements (break, continue, and pass). We also cover nested conditional statements, nested loops, and the use of the range() function for generating sequences of numbers. By understanding these concepts, you can create more efficient and versatile Python programs.</p>
</blockquote>
<h2 id="heading-definition-of-control-flow">Definition of control flow</h2>
<p>Control flow is the order in which a program's instructions are executed and is determined by conditional statements, loops, and function calls.</p>
<p>It allows a program to make decisions, repeat specific tasks, and organize code into reusable functions, enabling complex algorithms and dynamic behavior.</p>
<p>Without control flow, a program would just be a long laundry list of predefined instructions.</p>
<p>Although, control flow allows your program to be able to handle user inputs/behavior, and be able to pivot the outputs/behavior of the program based on the user inputs/behavior.</p>
<hr />
<h2 id="heading-overview-of-control-flow-in-python">Overview of control flow in Python</h2>
<p>In Python, control flow mainly consists of conditional statements (if, elif, and else), conditional/unconditional loops (for and while loops), and loop control statements (break, continue, and pass).</p>
<p>Another popular control flow method in other programming languages is switch/case statements. Up until very recently, Python didn't have the capability for switch/case statements. However, with the release of Python 3.10 in 2021, switch/case statements are now supported in Python.</p>
<p>I won't be covering switch/case statements in this article since they're still very new in the Python language, and they're not as widely used as the control flow methods I'll be covering.</p>
<p>Further, the logic of switch/case statements is very similar to if/elif/else statements. Traditionally, switch/case statements are used instead of if/elif/else statements if there are many different conditions/cases that the program has to handle.</p>
<p>Although, for general control flow, switch/case statements aren't always necessary.</p>
<hr />
<h2 id="heading-conditional-statements">Conditional Statements</h2>
<p>Conditional statements in Python are structured as a hierarchy of statements where the first statement is made with the "if" keyword. It should be noted that it is sufficient enough to <em>just</em> have an "if" statement. Although, you can also add another conditional statement starting with the "else" keyword after the "if" statement. Finally, if you need to control other conditions in your program, then you can do so with conditional statements placed in between the "if" and "else" statements and made with the "elif" keyword.</p>
<p>The logic behind conditional statements is:</p>
<ol>
<li><p>If this condition is met/if this is a true statement: do this...</p>
</li>
<li><p>Elif this condition is met/if this is a true statement: do this...</p>
</li>
<li><p>Else: do this...</p>
</li>
</ol>
<p>The if statement checks a condition, and if it's True, the code block within it is executed. The elif statement checks another condition if the previous conditions are not met. The else statement executes a code block if <strong>none</strong> of the previous conditions are met.</p>
<h3 id="heading-the-if-statement">The 'if' statement</h3>
<p>The if statement begins with the "if" keyword, followed by a statement that returns a Boolean value (True or False).</p>
<p>As such, when you're checking if a certain condition is met, you use the double equals, exclamation equals, greater than, less than, greater than or equals to, or less than or equals to.</p>
<p>Alternatively, you can also use the "is" keyword or "is not" keyword to check logical equivalence, although this is only reserved for comparing Boolean values and the None value.</p>
<p>In addition, you can also construct conditional statements by using "or" or "and" keywords to check if at least one condition or multiple conditions are met before executing a block of code.</p>
<h3 id="heading-syntax">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic syntax of if statement:</span>
<span class="hljs-keyword">if</span> <span class="hljs-number">1</span> == <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> != <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">3</span> &gt; <span class="hljs-number">2</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> &lt; <span class="hljs-number">3</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">4</span> &gt;= <span class="hljs-number">3</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">3</span> &lt;= <span class="hljs-number">4</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-literal">False</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == <span class="hljs-number">2</span> <span class="hljs-keyword">or</span> <span class="hljs-number">2</span> == <span class="hljs-number">3</span>: <span class="hljs-comment"># True statement </span>
    <span class="hljs-comment"># This line will execute since at least one condition is met</span>
    print(<span class="hljs-literal">True</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">3</span> == <span class="hljs-number">3</span> <span class="hljs-keyword">and</span> <span class="hljs-number">4</span> == <span class="hljs-number">4</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute since both conditions are met</span>
    print(<span class="hljs-literal">True</span>)
</code></pre>
<h3 id="heading-example">Example</h3>
<pre><code class="lang-python">age = <span class="hljs-number">21</span>

<span class="hljs-comment"># Basic if statement</span>
<span class="hljs-comment"># Check if the 'age' variable is greater than or equal to 21</span>
<span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">21</span>:
    <span class="hljs-comment"># This line will execute since the condition is met</span>
    print(<span class="hljs-string">"Do you want a glass of wine with your meal?"</span>)

<span class="hljs-comment">##############################</span>

animal = <span class="hljs-string">"cat"</span>

<span class="hljs-keyword">if</span> animal == <span class="hljs-string">"dog"</span>:
    <span class="hljs-comment"># This line WON'T execute since the condition is not met</span>
    print(<span class="hljs-string">"Do you wanna go for a walk outside?!"</span>)
</code></pre>
<h3 id="heading-the-elif-statement">The 'elif' statement</h3>
<p>Elif statements are placed in between the if statement and the optional else statement.</p>
<p>In one if/elif/else control flow structure, there can be multiple elif statements, but only 1 if statement and 1 else statement.</p>
<p>Similar to the if statement, the elif statement evaluates a comparison or multiple comparisons.</p>
<p>If the original condition in the if statement is not met, then the program will skip to the proceeding elif statement to see if that condition is met.</p>
<p>It's important to note that an if/elif/else control flow structure stops evaluating statements as soon as a condition is met. This means that even if you have multiple elif statements that evaluate to true, only the first elif statement that evaluates to true will be the block of code that is executed.</p>
<p>Also, since each conditional control flow structure has to start with an if statement, this means that the program knows when a new control flow structure you write another if statement line (even if that if statement line is written after another if statement or an elif statement in another control flow structure above it).</p>
<h3 id="heading-syntax-1">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic syntax of elif statement:</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == <span class="hljs-number">1</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"2 is equal to 1"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">2</span> != <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute</span>
    print(<span class="hljs-string">"2 is not equal to 1"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">2</span> &gt; <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This statement evaluates to true</span>
    <span class="hljs-comment"># But, this line won't execute since the elif above </span>
    <span class="hljs-comment"># evaluated to true</span>
    print(<span class="hljs-string">"2 is greater than 1"</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> &lt; <span class="hljs-number">3</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute</span>
    <span class="hljs-comment"># Therefore the program won't even evaluate the elif</span>
    <span class="hljs-comment"># statements below.</span>
    print(<span class="hljs-string">"2 is less than 3"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">4</span> &gt;= <span class="hljs-number">5</span>: <span class="hljs-comment"># False statement</span>
    print(<span class="hljs-string">"4 is greater than or equal to 5"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">3</span> &lt;= <span class="hljs-number">4</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-string">"3 is less than or equal to 4"</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-literal">False</span> <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute.</span>
    <span class="hljs-comment"># So, the program will evaluate the proceeding</span>
    <span class="hljs-comment"># elif statement.</span>
    print(<span class="hljs-string">"False is None"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-literal">True</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute, so the program will </span>
    <span class="hljs-comment"># not evaluate the elif statements below.</span>
    print(<span class="hljs-string">"True is not None"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">2</span> == <span class="hljs-number">2</span> <span class="hljs-keyword">or</span> <span class="hljs-number">2</span> == <span class="hljs-number">3</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-string">"2 is equal to 2, or 2 is equal to 3"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">3</span> == <span class="hljs-number">3</span> <span class="hljs-keyword">and</span> <span class="hljs-number">4</span> == <span class="hljs-number">4</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-literal">True</span>)
</code></pre>
<h3 id="heading-example-1">Example</h3>
<pre><code class="lang-python">age = <span class="hljs-number">10</span>

<span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">21</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"Do you want a glass of wine with your meal?"</span>)

<span class="hljs-keyword">elif</span> age &lt; <span class="hljs-number">12</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute</span>
    print(<span class="hljs-string">"Would you like a kids menu?"</span>)

<span class="hljs-comment">##############################</span>

animal = <span class="hljs-string">"dog"</span>

<span class="hljs-keyword">if</span> animal == <span class="hljs-string">"dog"</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute.</span>
    <span class="hljs-comment"># Program won't evaluate the elif statement below.</span>
    print(<span class="hljs-string">"Do you wanna go for a walk outside?!"</span>)

<span class="hljs-keyword">elif</span> animal == <span class="hljs-string">"cat"</span>: <span class="hljs-comment"># False statement</span>
    print(<span class="hljs-string">"Do you want some catnip?!"</span>)
</code></pre>
<h3 id="heading-the-else-statement">The 'else' statement</h3>
<p>Similar to the elif statement, the else statement is an optional statement that is placed at the very end of an if/elif/else control flow structure.</p>
<p>Unlike the if and elif statements, the else statement doesn't evaluate if a condition is met. Instead, the program will simply execute the code in the else block if all of the conditions above the else statement are not met.</p>
<h3 id="heading-syntax-2">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic syntax of elif statement:</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == <span class="hljs-number">1</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"2 is equal to 1"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># This line will execute, since the above condition wasn't met</span>
    print(<span class="hljs-string">"2 is not equal to 1"</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> != <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute</span>
    print(<span class="hljs-string">"2 is not equal to 1"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">2</span> &gt; <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-string">"2 is greater than 1"</span>)

<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"2 is equal to 1"</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">5</span> &lt; <span class="hljs-number">3</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"5 is less than 3"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">4</span> &gt;= <span class="hljs-number">5</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"4 is greater than or equal to 5"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">5</span> &lt;= <span class="hljs-number">4</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"5 is less than or equal to 4"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># The program will execute these lines, since</span>
    <span class="hljs-comment"># the above if/elif conditions were not met.</span>
    print(<span class="hljs-string">"5 is not less than 3"</span>)
    print(<span class="hljs-string">"4 is not greater than or equal to 5"</span>)
    print(<span class="hljs-string">"5 is not less than or equal to 4"</span>)
</code></pre>
<h3 id="heading-examples">Examples</h3>
<pre><code class="lang-python">age = <span class="hljs-number">18</span>

<span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">65</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"Would you like a senior discount?"</span>)

<span class="hljs-keyword">elif</span> age &lt; <span class="hljs-number">12</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"Would you like a kids menu?"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># This line will execute, since the above conditions</span>
    <span class="hljs-comment"># were not met.</span>
    print(<span class="hljs-string">"Do you have a student ID for a student discount?"</span>)

<span class="hljs-comment">##############################</span>

animal = <span class="hljs-string">"fish"</span>

<span class="hljs-keyword">if</span> animal == <span class="hljs-string">"fish"</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute.</span>
    print(<span class="hljs-string">"Check if aquarium needs fresh water"</span>)

<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Check if their water bowl needs more water"</span>)
</code></pre>
<h3 id="heading-nested-conditional-statements">Nested conditional statements</h3>
<p>Nested conditional statements in Python take basic conditional structures a step further. They involve placing one conditional statement inside another, allowing you to create more intricate decision-making logic within your code. This nested structure is particularly useful when you need to make more specific decisions within a broader context.</p>
<p>The key to understanding nested conditionals is the concept of indentation. In Python, indentation is not just a matter of style; it's crucial for defining the scope of code blocks. Indentation is what visually separates one level of nesting from another. When you nest one conditional statement inside another, the inner statement is indented to indicate that it's part of the outer block.</p>
<p>However, while nested conditionals are powerful, it's essential to balance complexity with readability. Excessive nesting can lead to code that is difficult to understand and maintain. In such cases, it's often a good practice to add comments to clarify the purpose of each level of nesting, making it easier for you and other developers to comprehend the code's logic.</p>
<h3 id="heading-syntax-3">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic syntax of nested conditional statements:</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == <span class="hljs-number">1</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"2 is equal to 1"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># This line will execute, since the above condition wasn't met</span>
    print(<span class="hljs-string">"2 is not equal to 1"</span>)
    <span class="hljs-comment"># The program will next evalutate this condition</span>
    <span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == <span class="hljs-number">2</span>: <span class="hljs-comment"># True statement</span>
        <span class="hljs-comment"># This line will execute since the above condition is met</span>
        print(<span class="hljs-string">"2 is equal to 2"</span>)

<span class="hljs-comment">##############################</span>

<span class="hljs-keyword">if</span> <span class="hljs-number">2</span> != <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    <span class="hljs-comment"># This line will execute</span>
    print(<span class="hljs-string">"2 is not equal to 1"</span>)

    <span class="hljs-comment"># The program will evalutate this condition next</span>
    <span class="hljs-keyword">if</span> <span class="hljs-number">2</span> == (<span class="hljs-number">1</span> + <span class="hljs-number">2</span>): <span class="hljs-comment"># False statement</span>
        <span class="hljs-comment"># This line won't execute since the above condition is not met</span>
        <span class="hljs-comment"># Program will now exit out of the original conditional flow structure</span>
        print(<span class="hljs-string">"1 + 2 = 2"</span>)

<span class="hljs-keyword">elif</span> <span class="hljs-number">2</span> &gt; <span class="hljs-number">1</span>: <span class="hljs-comment"># True statement</span>
    print(<span class="hljs-string">"2 is greater than 1"</span>)

<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"2 is equal to 1"</span>)
</code></pre>
<h3 id="heading-examples-1">Examples</h3>
<pre><code class="lang-python">age = <span class="hljs-number">18</span>

<span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">21</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"Would you like a glass of wine with your dinner?"</span>)
    <span class="hljs-comment"># This statement won't be evalutated</span>
    <span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">65</span>:
        print(<span class="hljs-string">"Would you like to use a senior discount?"</span>)

<span class="hljs-keyword">elif</span> age &lt; <span class="hljs-number">12</span>: <span class="hljs-comment"># False statement</span>
    <span class="hljs-comment"># This line won't execute</span>
    print(<span class="hljs-string">"Would you like a kids menu?"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># This line will execute, since the above conditions</span>
    <span class="hljs-comment"># were not met.</span>
    print(<span class="hljs-string">"Do you have a student ID for a student discount?"</span>)
</code></pre>
<hr />
<h2 id="heading-looping-constructs">Looping Constructs</h2>
<p>Loops in Python are essential for performing repetitive tasks and iterating over data structures. Python provides two primary types of loops: the for loop and the while loop.</p>
<ul>
<li><p>For loop: The for loop is used when you have a sequence of elements, such as a list, tuple, or string, and you want to iterate through each element one by one. The loop iterates over the elements in the sequence, and you can perform specific actions for each item within the loop's block</p>
</li>
<li><p>While loop: The while loop is another type of loop in Python. It is used when you want to repeat a block of code as long as a specific condition is true. The loop checks the condition before each iteration and stops once the condition becomes false.</p>
</li>
</ul>
<h3 id="heading-the-for-loop">The 'for' loop</h3>
<p>The for loop in Python is a fundamental construct that allows you to iterate through a sequence of items or elements. This sequence can be a list, tuple, string, dictionary, or any other iterable object. The for loop follows a simple and elegant syntax that provides a clear way to execute a block of code for each item in the sequence.</p>
<p>The primary purpose of the for loop is to automate repetitive tasks, where you need to perform the same operation on multiple items. Instead of writing the same code for each item, you can encapsulate the operation within the loop, and Python takes care of the iteration for you.</p>
<p>The for loop is not limited to numerical sequences; it can work with any iterable data structure, including strings, where it iterates through each character, or dictionaries, where it iterates through keys or values.</p>
<h3 id="heading-syntax-4">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic for loop syntax:</span>

l = [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>]

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> l:
    <span class="hljs-comment"># Prints each element in l in sequential order</span>
    print(i)
</code></pre>
<h3 id="heading-examples-2">Examples</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Example nesting a conditional statement inside a for loop</span>

lucky_number = <span class="hljs-number">3</span>
l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

<span class="hljs-comment"># Iterate through each element in l</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> l:
    <span class="hljs-comment"># For each element of l, check if it equals the lucky number</span>
    <span class="hljs-keyword">if</span> i == lucky_number:
        <span class="hljs-comment"># This line will execute ONCE</span>
        print(<span class="hljs-string">"Lucky number "</span> + str(lucky_number))
</code></pre>
<h3 id="heading-the-range-function">The 'range()' function</h3>
<p>The range() function in Python is a versatile and essential tool for generating sequences of numbers. It is commonly used in conjunction with for loops to iterate over a range of values. The range() function creates a special type of iterable called a range object, which represents an immutable sequence of numbers.</p>
<p>The range() function is not limited to for loops; you can also convert a range object to a list or use it in other contexts where iterable sequences are required. It's a valuable tool for creating and managing sequences of numbers efficiently, which is especially useful in various programming scenarios, including counting, iterating, and indexing.</p>
<p>The arguments of the range() function are as follows:</p>
<ul>
<li><p><strong>start</strong> (optional) is the initial value of the sequence. If omitted, it defaults to 0.</p>
</li>
<li><p><strong>stop</strong> is the endpoint of the sequence, and the generated sequence will not include this value.</p>
</li>
<li><p><strong>step</strong> (optional) is the increment by which each number in the sequence increases. It defaults to 1 if not provided.</p>
</li>
</ul>
<pre><code class="lang-python">start = <span class="hljs-number">10</span>
stop = <span class="hljs-number">20</span>
step = <span class="hljs-number">2</span>

<span class="hljs-comment"># This loop will start at i = 10, stop executing once i = 20, </span>
<span class="hljs-comment"># and increment i by 2 each iteration</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(start, stop, step):
    print(i)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># 10</span>
<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 14</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 18</span>

<span class="hljs-comment">##############################</span>
<span class="hljs-comment"># Example with just the "stop" argument</span>
<span class="hljs-comment"># This loop will start at i = 0, stop executing once i = 10,</span>
<span class="hljs-comment"># and increment i by 1 each iteration.</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    print(i ** <span class="hljs-number">2</span>)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 25</span>
<span class="hljs-comment"># 36</span>
<span class="hljs-comment"># 49</span>
<span class="hljs-comment"># 64</span>
<span class="hljs-comment"># 81</span>
</code></pre>
<h3 id="heading-the-while-loop">The 'while' loop</h3>
<p>The while loop is a powerful control structure that allows you to repeatedly execute a block of code as long as a specific condition remains true. Unlike the for loop, which is ideal for iterating through sequences, the while loop is excellent when you don't know in advance how many iterations you'll need, but you do know the condition under which the loop should continue.</p>
<p>The loop starts by evaluating the condition. If the condition is True, the code block beneath the while statement is executed. After the block is executed, the condition is evaluated again, and the loop continues to run as long as the condition remains True.</p>
<p>One key feature of the while loop is its adaptability. It's not limited to counting or numeric operations; it can be used for various tasks, such as searching through data or managing program flow based on dynamic conditions. However, it's crucial to ensure that the condition in a while loop will eventually become False, or you risk creating an infinite loop, which can lead to a program becoming unresponsive or even crashing.</p>
<h3 id="heading-syntax-5">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># Basic while loop syntax:</span>

x = <span class="hljs-number">0</span>
y = <span class="hljs-number">10</span>

<span class="hljs-comment"># While this condition remains true</span>
<span class="hljs-keyword">while</span> x &lt; y:
    <span class="hljs-comment"># This loop will stop executing once x &gt;= y</span>
    <span class="hljs-comment"># Each iteration, we're incrementing x by 1</span>
    <span class="hljs-comment"># and decrementing y by 1</span>
    x += <span class="hljs-number">1</span>
    y -= <span class="hljs-number">1</span>
    print(<span class="hljs-string">"x: "</span>, x)
    print(<span class="hljs-string">"y: "</span>, y)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># x:  1</span>
<span class="hljs-comment"># y:  9</span>
<span class="hljs-comment"># x:  2</span>
<span class="hljs-comment"># y:  8</span>
<span class="hljs-comment"># x:  3</span>
<span class="hljs-comment"># y:  7</span>
<span class="hljs-comment"># x:  4</span>
<span class="hljs-comment"># y:  6</span>
<span class="hljs-comment"># x:  5</span>
<span class="hljs-comment"># y:  5</span>

<span class="hljs-comment"># As you can see, this loop will eventually stop since there's a moment</span>
<span class="hljs-comment"># when x is no longer less than y (when x = y = 5)</span>
</code></pre>
<h3 id="heading-nested-loops">Nested loops</h3>
<p>Nested loops in Python refer to the practice of placing one loop inside another loop. This approach allows you to create more complex and multi-dimensional iterations. While Python supports both for and while loops, nested loops are often used in scenarios where you need to work with arrays, matrices, or perform operations on multiple levels of data.</p>
<p>The key concept behind nested loops is that the inner loop completes its entire cycle for each iteration of the outer loop. This results in all possible combinations of the inner and outer loop iterations being processed. For example, if you have a list of students and a list of subjects, you can use nested loops to generate all possible combinations of students and subjects</p>
<p>Nested loops are also used to work with multi-dimensional data structures, like lists of lists (2D arrays) or matrices. You can use nested loops to traverse and manipulate elements within these data structures.</p>
<p>It's important to consider the performance implications of nested loops, especially when dealing with large datasets. The time complexity of nested loops is often proportional to the product of the lengths of the sequences they iterate over. So, if you have two nested loops, each iterating over a list of length n, the total number of iterations becomes n * n = n^2, which can be substantial for large n.</p>
<h3 id="heading-syntax-6">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># nested for loop</span>

<span class="hljs-comment"># Outer loop will start at 1, stop at 6, increment by 1</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
    <span class="hljs-comment"># Inner loop will start at 1, stop at 5, increment by 1</span>
    <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>):
        result = i * j
        print(i, <span class="hljs-string">" * "</span>, j, <span class="hljs-string">" = "</span>, result)

<span class="hljs-comment"># Output:    </span>
<span class="hljs-comment"># 1  *  1  =  1</span>
<span class="hljs-comment"># 1  *  2  =  2</span>
<span class="hljs-comment"># 1  *  3  =  3</span>
<span class="hljs-comment"># 1  *  4  =  4</span>
<span class="hljs-comment"># 2  *  1  =  2</span>
<span class="hljs-comment"># 2  *  2  =  4</span>
<span class="hljs-comment"># 2  *  3  =  6</span>
<span class="hljs-comment"># 2  *  4  =  8</span>
<span class="hljs-comment"># 3  *  1  =  3</span>
<span class="hljs-comment"># 3  *  2  =  6</span>
<span class="hljs-comment"># 3  *  3  =  9</span>
<span class="hljs-comment"># 3  *  4  =  12</span>
<span class="hljs-comment"># 4  *  1  =  4</span>
<span class="hljs-comment"># 4  *  2  =  8</span>
<span class="hljs-comment"># 4  *  3  =  12</span>
<span class="hljs-comment"># 4  *  4  =  16</span>
<span class="hljs-comment"># 5  *  1  =  5</span>
<span class="hljs-comment"># 5  *  2  =  10</span>
<span class="hljs-comment"># 5  *  3  =  15</span>
<span class="hljs-comment"># 5  *  4  =  20</span>


<span class="hljs-comment"># nested for and while loop</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    j = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span> j &lt; i + <span class="hljs-number">1</span>:
        print(<span class="hljs-string">"*"</span>, end=<span class="hljs-string">" "</span>)
        j += <span class="hljs-number">1</span>
    print()

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># * </span>
<span class="hljs-comment"># * * </span>
<span class="hljs-comment"># * * * </span>
<span class="hljs-comment"># * * * * </span>
<span class="hljs-comment"># * * * * * </span>


<span class="hljs-comment"># Nested while loop</span>
outer_count = <span class="hljs-number">1</span>

<span class="hljs-keyword">while</span> outer_count &lt;= <span class="hljs-number">3</span>:
    inner_count = <span class="hljs-number">1</span>

    <span class="hljs-keyword">while</span> inner_count &lt;= <span class="hljs-number">3</span>:
        print(<span class="hljs-string">"Outer Count: "</span>, outer_count, <span class="hljs-string">"Inner Count: "</span>, inner_count)
        inner_count += <span class="hljs-number">1</span>

    outer_count += <span class="hljs-number">1</span>

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># Outer Count:  1 Inner Count:  1</span>
<span class="hljs-comment"># Outer Count:  1 Inner Count:  2</span>
<span class="hljs-comment"># Outer Count:  1 Inner Count:  3</span>
<span class="hljs-comment"># Outer Count:  2 Inner Count:  1</span>
<span class="hljs-comment"># Outer Count:  2 Inner Count:  2</span>
<span class="hljs-comment"># Outer Count:  2 Inner Count:  3</span>
<span class="hljs-comment"># Outer Count:  3 Inner Count:  1</span>
<span class="hljs-comment"># Outer Count:  3 Inner Count:  2</span>
<span class="hljs-comment"># Outer Count:  3 Inner Count:  3</span>
</code></pre>
<hr />
<h2 id="heading-loop-control-statements">Loop Control Statements</h2>
<p>Loop control statements are essential tools for managing the flow of loops, whether they are for or while loops. These statements allow you to modify the behavior of a loop, control the iteration process, and handle exceptional conditions. In Python, there are three primary loop control statements: break, continue, and pass.</p>
<ol>
<li><p><strong>break</strong>: The break statement is used to prematurely exit a loop before it reaches its normal conclusion. When a break statement is encountered within a loop, the loop is terminated immediately, and the program continues executing the code after the loop.</p>
</li>
<li><p><strong>continue</strong>: The continue statement is used to skip the rest of the current iteration of a loop and move to the next iteration. It is handy when you want to avoid executing certain code within a loop for specific iterations while continuing with the remaining iterations.</p>
</li>
<li><p><strong>pass</strong>: The pass statement is a placeholder that does nothing. It's often used when a statement is syntactically required but you don't want to perform any action. It can be helpful when you're in the process of developing code and need to define a placeholder for future implementation.</p>
</li>
</ol>
<p>These loop control statements give you the flexibility to handle various scenarios efficiently. They allow you to control the flow of loops based on specific conditions, skip iterations when needed, and create placeholders for future code development. By mastering these control statements, you can write more versatile and robust loops in your Python programs.</p>
<h3 id="heading-the-break-statement">The 'break' statement</h3>
<p>The break statement is particularly useful in situations where you need to stop the execution of a loop based on a specific condition or handle exceptions.</p>
<p>When Python encounters a break statement within a loop, it immediately terminates the loop and continues executing the code after the loop.</p>
<p>It's worth noting that while the break statement is a valuable tool, its use should be handled with care. Misuse of the break statement can lead to unexpected program behavior or make the code less readable. As such, it's important to document the intended behavior and reasons for using the break statement when working on larger and more complex projects.</p>
<h3 id="heading-syntax-7">Syntax</h3>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>]
target = <span class="hljs-number">7</span>

<span class="hljs-comment"># This loop will iterate through each element of the 'numbers' list</span>
<span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
    <span class="hljs-comment"># For each number in 'numbers' list, check if the number is</span>
    <span class="hljs-comment"># equal to the target (7).</span>
    <span class="hljs-keyword">if</span> number == target:
        <span class="hljs-comment"># If the number in iteration is equal to the target,</span>
        <span class="hljs-comment"># print the statement below and exit the for loop.</span>
        print(<span class="hljs-string">"Found the target number: "</span>, target)
        <span class="hljs-keyword">break</span>

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># Found the target number:  7</span>

<span class="hljs-comment"># As you can see with the above example, the break statement allows</span>
<span class="hljs-comment"># us to save compute time by automatically ending the loop once</span>
<span class="hljs-comment"># we have the information that we need.</span>
</code></pre>
<h3 id="heading-the-continue-statement">The 'continue' statement</h3>
<p>The continue statement is a versatile control structure in Python that allows you to skip the remaining code within the current iteration of a loop and move to the next iteration. It's particularly useful when you want to selectively exclude certain iterations from being processed within a loop based on specific conditions.</p>
<p>Another common use of the continue statement is to control loop behavior when processing data. For example, in data validation or data processing tasks, you may want to skip over certain entries or conditions and continue with the rest of the data.</p>
<p>As with any control structure, it's important to use the continue statement judiciously and document your code appropriately. Overusing continue statements or using them inappropriately can lead to code that is hard to understand and maintain.</p>
<h3 id="heading-syntax-8">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># syntax of the continue statement</span>

<span class="hljs-comment"># Start at 1, end at 11</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
    <span class="hljs-comment"># If i mod 3 is equal to 0, then don't do anything and continue iterating</span>
    <span class="hljs-keyword">if</span> i % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">continue</span>
    <span class="hljs-comment"># This line below will only execute when the above condition is not met.</span>
    <span class="hljs-comment"># In other words, if i mod 3 is not equal to 0.</span>
    print(i)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 7</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 10</span>
</code></pre>
<h3 id="heading-the-pass-statement">The 'pass' statement</h3>
<p>The pass statement is a simple, yet valuable, control structure in Python that serves as a placeholder for future code. It is a no-operation statement, meaning it does nothing when executed. The primary purpose of the pass statement is to provide a syntactically required statement that doesn't perform any action, allowing you to create empty code blocks, functions, or classes without triggering syntax errors.</p>
<p>The pass statement is useful in several situations:</p>
<ul>
<li><p><strong>Creating a Placeholder</strong>: Often, during the development of a program, you may need to define functions, classes, or blocks of code that are not yet implemented. In such cases, you can use the pass statement to create a placeholder until you are ready to add the actual code. This allows you to maintain code integrity and readability while indicating that certain parts of the program are intentionally left incomplete.</p>
</li>
<li><p><strong>Avoiding Syntax Errors</strong>: In Python, certain structures, such as loops or conditional statements, require an indented block of code, even if that code is empty. Without the pass statement, an empty block would trigger a syntax error. Using pass prevents such errors and allows you to maintain proper code structure.</p>
</li>
<li><p><strong>Temporary Bypass</strong>: The pass statement can also be used to temporarily bypass certain parts of code, helping you to debug or test your program while excluding specific sections without deleting them.</p>
</li>
</ul>
<h3 id="heading-syntax-9">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-comment"># pass in if-else statement</span>
car = {
<span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
<span class="hljs-string">"miles"</span>: <span class="hljs-number">80000</span>,
<span class="hljs-string">"year"</span>: <span class="hljs-number">2018</span>}

<span class="hljs-keyword">if</span> car[<span class="hljs-string">"miles"</span>] &gt;= <span class="hljs-number">100000</span>:
    <span class="hljs-keyword">pass</span>  <span class="hljs-comment"># Placeholder for future code</span>

<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Your car is still under 100,000 miles"</span>)
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope after reading this article, you now have a deeper understanding of the concept of controlling the flow of Python programs, and how to implement the best practices in controlling flow.</p>
<p>In this article, you learned the significance of conditional statements like 'if,' 'elif,' and 'else' in enabling the execution of different code blocks based on specific conditions. Additionally, you explored the versatility of loops, both 'for' and 'while,' in facilitating repetitive tasks.</p>
<p>If you have any questions or suggestions for a topic you want me to cover in the future, then feel free to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
]]></content:encoded></item><item><title><![CDATA[An Introduction to the Binary Tree: One of the Essential Data Structures in Computer Science]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases. Read the full disclosure

In this article, we explore binary trees and their importance in computer ...]]></description><link>https://scrappedscript.com/an-introduction-to-the-binary-tree-one-of-the-essential-data-structures-in-computer-science</link><guid isPermaLink="true">https://scrappedscript.com/an-introduction-to-the-binary-tree-one-of-the-essential-data-structures-in-computer-science</guid><category><![CDATA[BinaryTrees]]></category><category><![CDATA[data structures]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Thu, 19 Oct 2023 17:35:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Xi-yGUFC1R0/upload/11693068b567fc6279910dc4a1da654a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.</em> <a target="_blank" href="https://scrappedscript.com/disclaimers"><strong>Read the full disclosure</strong></a></p>
<blockquote>
<p>In this article, we explore binary trees and their importance in computer science. We cover the terminology, four main traversal methods (preorder, inorder, postorder, and level order), and some basic operations such as insertion, deletion, and searching. By understanding binary trees and their applications, you can optimize data structures and improve your problem-solving skills in computer science and mathematics.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://images.unsplash.com/photo-1596496181871-9681eacf9764?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1486&amp;q=80" alt="woman writing digital logic on whiteboard" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/log-base-two">Log Base Two</a>, a series dedicated to the relationship between math and computer science.</p>
<p>Just to give a bit of background on my experience in math, I've excelled in a total of 10 college courses in math:</p>
<ol>
<li><p><strong>Single-variable differential calculus</strong></p>
</li>
<li><p><strong>Single-variable integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus of vector-valued functions</strong></p>
</li>
<li><p><strong>Linear Algebra</strong></p>
</li>
<li><p><strong>Differential equations</strong></p>
</li>
<li><p><strong>Probability and statistics</strong></p>
</li>
<li><p><strong>Data analysis using R programming language</strong></p>
</li>
<li><p><strong>Multivariate statistics</strong></p>
</li>
<li><p><strong>Discrete math</strong></p>
</li>
</ol>
<p>For a large majority of those 10 classes, I ended up with A's.</p>
<p>Although, before college, I struggled a lot with math in the classroom, even though math had always been my favorite subject since I was in elementary school. I found it hard to truly grasp the concepts taught because my high school teachers were too focused on skill assessment. Instead of focusing on the actual concept being taught, I was too worried about how I was going to pass the test the following week.</p>
<p>Once I got to college, I realized that your math grade (or any grade for that matter) truly doesn't define your potential. Further, I'd argue that your success in math <em>education</em> is heavily influenced by the quality of the teacher/professor's teaching.</p>
<p>My mission with this series is to show other people that math isn't so scary if you break down mathematical concepts into digestible bouts of information and investigate use cases of math in your primary field of interest (in this case, computer science). Along the way, I hope to also supplement your math education with quality content. I believe that <strong>everyone</strong> is capable of learning and truly loving mathematics.</p>
<p><strong>New articles in this series are posted every Thursday!</strong></p>
<hr />
<p><a target="_blank" href="https://amzn.to/3tul3lG"><img src="https://m.media-amazon.com/images/G/01/pvc/PV_Benefits_Devices_UPDATED.png" alt="two people surrounded by phone, tablet, and tv" class="image--center mx-auto" /></a></p>
<p><a target="_blank" href="https://amzn.to/46T71IH">Prime Video Channels free trial</a></p>
<p>Enjoy Thursday Night Football and other Amazon Originals, popular movies, and hit TV shows — all available with your Prime membership.</p>
<p>Members can also subscribe to 100+ channels and get special deals to rent or buy new release movies and more.</p>
<p>If you're not a Prime member yet, then start your <a target="_blank" href="https://amzn.to/403dfDW">free 30-day trial</a> today!</p>
<p><a target="_blank" href="https://amzn.to/3FkrA5h"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<hr />
<h2 id="heading-i-overview-of-binary-trees">I. Overview of binary trees</h2>
<p><img src="https://images.unsplash.com/photo-1506670223639-c9c8ab811391?auto=format&amp;fit=crop&amp;q=80&amp;w=1470&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="dead tree with branches" class="image--center mx-auto" /></p>
<p>In math, a binary tree is a type of graph that falls under the category of trees (as implied by the name).</p>
<p>Due to the simplistic structure and logic of binary trees, they've played an integral role as one of the foundational data structures used in computer science.</p>
<p>Like all data structures, trees are simply representations of a set of data points (aka nodes) that are connected via edges.</p>
<p>The best way to think of binary trees is to imagine a family ancestral tree (sort of).</p>
<p>In a family ancestral tree, you have a hierarchy of people defined by generation. At the very bottom are the youngest, and at the very top are the oldest.</p>
<p>Additionally, no one in the family ancestral tree is directly connected to any family member above the level right before them (their parents). Similarly, no one in the family ancestral tree is directly connected to any family member below the level right after them (their children).</p>
<p>Binary trees are structured similarly but not as complicated.</p>
<p>To start, binary trees begin with a single node (called the root node) at the highest level of the hierarchy.</p>
<p>Also, instead of having 2 parents, each node in a binary tree only has 1 parent.</p>
<p>Finally, each node can have no more than 2 child nodes (simply referred to as the left and right child).</p>
<h3 id="heading-a-importance-of-binary-trees-in-computer-science">a) Importance of binary trees in computer science</h3>
<p>The entire motivation behind the study of data structures in computer science is to understand which data structures are most efficient for storing data for a particular type of application, algorithm, or task.</p>
<p>The idea is that by optimizing your data structure, you can shorten the time it takes to build the data structure based on the nature of your data, optimize the time it takes to add or retrieve data and optimize the size of the data structure in computer memory.</p>
<p>In computer science, binary trees are typically used in data compression applications, database indexing, sorting algorithms, decision trees in supervised machine learning, and much more.</p>
<h2 id="heading-ii-binary-tree-terminology">II. Binary tree terminology</h2>
<pre><code class="lang-plaintext">    1 &lt;-- root/parent node
   / \
  2   3 &lt;-- parent/child node
 / \   \
4   5   6 &lt;-- child/leaf node

levels: 3

__________________________

subtree with root at node 2

  2
 / \
4   5
</code></pre>
<h3 id="heading-a-node">a) Node</h3>
<p>A node is a single data point.</p>
<p>In the above binary tree, all of those numbers are values held within nodes.</p>
<p>Since binary trees are just sets, you can also think of the data within a node as being an element of the set defined by the binary tree.</p>
<h3 id="heading-b-root">b) Root</h3>
<p>The root of a binary tree is the node that is at the highest level within the tree.</p>
<p>In the above binary tree, the node containing the value 1 is the root node.</p>
<p>You can think of the root as being the "starting point" for the binary tree.</p>
<p>From the root, edges branch out to child nodes of the root, and then those child nodes of the root branch out edges to their child nodes and so on until the tree is populated with all of the data points.</p>
<p>The root node is the only node that doesn't have a parent node.</p>
<h3 id="heading-c-parent-child-and-sibling-nodes">c) Parent, child, and sibling nodes</h3>
<p>A parent node is any node that has at least 1 child node. More specifically, a parent node is a parent to the node(s) in the level right below it that it's connected to via edges.</p>
<p>In the above binary tree, 2 is the left child of the root node and is also the parent of its left child (4) and its right child (5).</p>
<p>A child node is any node that has a parent node. By definition, every node in a binary tree is a child node except for the root node. Child nodes are classified even further by which side they fall under their parent node. If a child is to the left of the parent node, then it's called the "left child". Alternatively, if a child is on the right of the parent node, then it's called the "right child".</p>
<p>A sibling node is any child node that is connected to the same parent node as another child node. By definition, each node can have either 0 or 1 sibling node.</p>
<h3 id="heading-d-leaf-nodes">d) Leaf nodes</h3>
<p>A lead node is any node that does not have any child nodes.</p>
<p>In the above binary tree, the node containing the value 4 is a leaf node.</p>
<p>By definition, all of the nodes in the bottom level of the tree are considered leaf nodes.</p>
<h3 id="heading-e-level-and-height">e) Level and height</h3>
<p>In a binary tree, the hierarchy of each node about all the other nodes is determined by its level and height.</p>
<p>The highest level is level 1, and this is the level that contains the root node. From there, the child nodes of the root node makeup level 2 and so on.</p>
<p>The height of a node is defined by the longest path from that node to a leaf node. The height is measured in units of edges. So if a binary tree has 3 levels, this would mean that the root node has a height of 2 (since you'd have to traverse 2 edges from the root node to a leaf node in the bottom level). By definition, each leaf node has a height of 0.</p>
<h3 id="heading-f-subtree">f) Subtree</h3>
<p>We can break down a binary tree into subtrees where we define the root node and then build our subtree by including the edge(s) and child node(s) of that node and so on.</p>
<h2 id="heading-iii-binary-tree-traversal">III. Binary tree traversal</h2>
<p>One important question to ask with any data structure is: what are the ways that I can sequentially list out every single data point contained in the data structure?</p>
<p>For binary trees, there are 4 main ways that we can traverse the tree and be able to visit each node.</p>
<p>Besides simply being able to return each node contained in a binary tree, tree traversals also serve as a required step in many of the operations that can be performed on binary trees as you'll see in the section further down.</p>
<h3 id="heading-a-preorder">a) Preorder</h3>
<p>The basic principle of preorder traversal is to start at the root node, then visit each node on the left side of the tree, followed by the right side of the tree.</p>
<p>When we do preorder traversal, we think of each node as being a root node of its own subtree. As such, the algorithm used in preorder traversal is recursive.</p>
<p>The preorder traversal algorithm works like this in Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Create node class to create nodes as objects</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value</span>):</span>
        self.value = value
        self.left = <span class="hljs-literal">None</span>
        self.right = <span class="hljs-literal">None</span>

<span class="hljs-comment"># Pass in the root node to begin the algorithm</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">preorder_traversal</span>(<span class="hljs-params">root</span>):</span>

    <span class="hljs-comment"># Condition to stop recursion if node doesn't have child</span>
    <span class="hljs-keyword">if</span> root <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">return</span> []

    result = []
    <span class="hljs-comment"># Start at root</span>
    result.append(root.value)
    <span class="hljs-comment"># Recursively traverse left subtree</span>
    result += preorder_traversal(root.left)
    <span class="hljs-comment"># Recursively traverse right subtree</span>
    result += preorder_traversal(root.right)

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

<span class="hljs-comment">#example</span>

<span class="hljs-comment">#    1</span>
<span class="hljs-comment">#   / \</span>
<span class="hljs-comment">#  2   3</span>
<span class="hljs-comment"># / \   \</span>
<span class="hljs-comment">#4   5   6</span>
<span class="hljs-comment"># preorder traversal:</span>
<span class="hljs-comment"># 1, 2, 4, 5, 3, 6</span>

root = Node(<span class="hljs-number">1</span>)
root.left = Node(<span class="hljs-number">2</span>)
root.right = Node(<span class="hljs-number">3</span>)

root.left.left = Node(<span class="hljs-number">4</span>)
root.left.right = Node(<span class="hljs-number">5</span>)

root.right.right = Node(<span class="hljs-number">6</span>)

print(preorder_traversal(root))
</code></pre>
<h3 id="heading-b-inorder">b) Inorder</h3>
<p>With inorder traversal, we start by traversing the left subtree, then the root node, followed by the right subtree.</p>
<p>In Python, we'd implement the inorder traversal like this:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value</span>):</span>
        self.value = value
        self.left = <span class="hljs-literal">None</span>
        self.right = <span class="hljs-literal">None</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inorder_traversal</span>(<span class="hljs-params">root</span>):</span>

    <span class="hljs-keyword">if</span> root <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">return</span> []

    result = []

    result += inorder_traversal(root.left)
    result.append(root.value)
    result += inorder_traversal(root.right)

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

<span class="hljs-comment">#example</span>

<span class="hljs-comment">#    1</span>
<span class="hljs-comment">#   / \</span>
<span class="hljs-comment">#  2   3</span>
<span class="hljs-comment"># / \   \</span>
<span class="hljs-comment">#4   5   6</span>
<span class="hljs-comment"># inorder traversal:</span>
<span class="hljs-comment"># 4, 2, 5, 1, 3, 6</span>

root = Node(<span class="hljs-number">1</span>)
root.left = Node(<span class="hljs-number">2</span>)
root.right = Node(<span class="hljs-number">3</span>)

root.left.left = Node(<span class="hljs-number">4</span>)
root.left.right = Node(<span class="hljs-number">5</span>)

root.right.right = Node(<span class="hljs-number">6</span>)

print(inorder_traversal(root))
</code></pre>
<p>If you notice, the code for inorder traversal is almost identical to the code for preorder traversal, except we switched the order for two lines: <code>result += inorder_traversal(root.left)</code> and <code>result.append(root.value)</code>.</p>
<h3 id="heading-c-postorder">c) Postorder</h3>
<p>In postorder traversal, we start by traversing the left subtree, then the right subtree, followed by the root node.</p>
<p>With Python, we could implement postorder traversal like this:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value</span>):</span>
        self.value = value
        self.left = <span class="hljs-literal">None</span>
        self.right = <span class="hljs-literal">None</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">postorder_traversal</span>(<span class="hljs-params">root</span>):</span>

    <span class="hljs-keyword">if</span> root <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">return</span> []

    result = []

    result += postorder_traversal(root.left)
    result += postorder_traversal(root.right)
    result.append(root.value)

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

<span class="hljs-comment">#example</span>

<span class="hljs-comment">#    1</span>
<span class="hljs-comment">#   / \</span>
<span class="hljs-comment">#  2   3</span>
<span class="hljs-comment"># / \   \</span>
<span class="hljs-comment">#4   5   6</span>
<span class="hljs-comment"># postorder traversal:</span>
<span class="hljs-comment"># 4, 5, 2, 6, 3, 1</span>

root = Node(<span class="hljs-number">1</span>)
root.left = Node(<span class="hljs-number">2</span>)
root.right = Node(<span class="hljs-number">3</span>)

root.left.left = Node(<span class="hljs-number">4</span>)
root.left.right = Node(<span class="hljs-number">5</span>)

root.right.right = Node(<span class="hljs-number">6</span>)

print(postorder_traversal(root))
</code></pre>
<p>As you can see, postorder traversal is almost identical to inorder traversal except we switch two lines of code: <code>result += postorder_traversal(root.right)</code> and <code>result.append(root.value)</code>.</p>
<h3 id="heading-d-level-order">d) Level order</h3>
<p>Out of all the traversal methods here, level order is the most unique.</p>
<p>The main idea of level order traversal is to traverse the tree by level. Starting at level 1 (the root node), then visiting each node in level 2, and so on.</p>
<p>Since we typically don't define a node's level in programming, level order traversal relies on the use of a list traditionally called a queue. In the queue, we sequentially store the left and right child nodes of the current root node. Then, we remove the first node in the queue and recursively run the function on that first node we removed from the queue.</p>
<p>With Python, we could write a level order algorithm like this:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value</span>):</span>
        self.value = value
        self.left = <span class="hljs-literal">None</span>
        self.right = <span class="hljs-literal">None</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">level_order_traversal</span>(<span class="hljs-params">root, queue = []</span>):</span>

    result = []

    <span class="hljs-comment"># Add in current node value</span>
    result.append(root.value)

    <span class="hljs-keyword">if</span> root.left <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        <span class="hljs-comment"># If current node has left child, add it to queue</span>
        queue.append(root.left)

    <span class="hljs-keyword">if</span> root.right <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        <span class="hljs-comment"># If current node has right child, add it to queue</span>
        queue.append(root.right)

    <span class="hljs-comment"># If there are nodes in the queue:</span>
    <span class="hljs-keyword">if</span> len(queue) &gt; <span class="hljs-number">0</span>:
        <span class="hljs-comment"># Simultaneously remove the first node from the queue</span>
        <span class="hljs-comment"># and define/store it in a variable</span>
        node = queue.pop(<span class="hljs-number">0</span>)
        <span class="hljs-comment"># Recursively run algorithm</span>
        result += level_order_traversal(node, queue)

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

<span class="hljs-comment">#example</span>

<span class="hljs-comment">#    1</span>
<span class="hljs-comment">#   / \</span>
<span class="hljs-comment">#  2   3</span>
<span class="hljs-comment"># / \   \</span>
<span class="hljs-comment">#4   5   6</span>
<span class="hljs-comment"># level order traversal:</span>
<span class="hljs-comment"># 1, 2, 3, 4, 5, 6</span>

root = Node(<span class="hljs-number">1</span>)
root.left = Node(<span class="hljs-number">2</span>)
root.right = Node(<span class="hljs-number">3</span>)

root.left.left = Node(<span class="hljs-number">4</span>)
root.left.right = Node(<span class="hljs-number">5</span>)

root.right.right = Node(<span class="hljs-number">6</span>)

print(level_order_traversal(root))
</code></pre>
<h2 id="heading-iv-binary-tree-operations">IV. Binary tree operations</h2>
<p>There are many different operations that we can perform on binary trees to return information about the tree, return nodes, return subtrees, or modify the data within a binary tree.</p>
<p>I'm going to cover some of the most basic operations that can be performed on binary trees, but again, this is not even close to being a comprehensive list of all the operations you can perform.</p>
<h3 id="heading-a-insertion">a) Insertion</h3>
<p>Insertion involves adding a new node to the binary tree while still maintaining the original structure, properties and logic of the binary tree.</p>
<p>To insert a node into a binary tree, we start at the root node. From the root node, we compare the new node's value with the root node's value. If the new value is less than the root node's value, compare the new node to the left child; otherwise, compare the new node to the right child. We repeat this process until we find an empty spot to place the new node in the bottom level.</p>
<h3 id="heading-b-deletion">b) Deletion</h3>
<p>Alternative to adding new nodes with insertion, we can remove nodes with deletion.</p>
<p>The basic principle of deletion is that when we remove a node, we're technically replacing the old node with a node that will fill the same spot in the tree that the old node was.</p>
<p>The node that replaces the deleted node is the lowest and rightmost node.</p>
<p>In practice, this is accomplished by first locating the node we want to delete and the lowest, rightmost node. After that, we assign the value of the node we want to remove to the value of the lowest, rightmost node's value. Finally, we delete the lowest, rightmost node from the tree.</p>
<h3 id="heading-c-searching">c) Searching</h3>
<p>If we want to see if a particular node is an element of the binary tree, then we use an operation called searching.</p>
<p>We first choose a traversal technique, then we define our traversal algorithm to stop once the node we're searching for is the current node.</p>
<p>If the entire tree is traversed and the node isn't found, then we'll know that the node isn't an element of the binary tree.</p>
<h2 id="heading-v-conclusion">V. Conclusion</h2>
<p>After reading this article, I hope you now understand what binary trees are and the different operations that we can perform on them.</p>
<p>You learned about all the different components/terminology of binary trees, the 4 main methods of traversing a binary tree, and some of the basic operations that we can perform on binary trees.</p>
<p>If you have any lingering questions, please feel free to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter so you never miss out on when I post new content.</p>
]]></content:encoded></item><item><title><![CDATA[Enter Flow State While Programming to Boost Your Productivity and Creativity]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Apple Performance Partner, I earn from qualifying purchases. Read the full disclosure

In this article, we explore the concept of flow state, a psycholo...]]></description><link>https://scrappedscript.com/enter-flow-state-while-programming-to-boost-your-productivity-and-creativity</link><guid isPermaLink="true">https://scrappedscript.com/enter-flow-state-while-programming-to-boost-your-productivity-and-creativity</guid><category><![CDATA[flow]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 17 Oct 2023 18:04:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cckf4TsHAuw/upload/b8d846d44680f287ea5580afd2e56573.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Apple Performance Partner, I earn from qualifying purchases.</em> <a target="_blank" href="https://scrappedscript.com/disclaimers"><strong>Read the full disclosure</strong></a></p>
<blockquote>
<p>In this article, we explore the concept of flow state, a psychological term describing the feeling of complete immersion and focus in a challenging or creative activity. We discuss the factors that influence entering a flow state, including skill level, challenge level, environment, and mindset. Additionally, we provide techniques to enter and enhance the flow state, such as setting clear goals, eliminating distractions, creating a dedicated workspace, practicing mindfulness, and encouraging exploration. By understanding and harnessing the power of the flow state, individuals can boost their productivity, creativity, and overall satisfaction in their work.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p>This article is part of a series called <a target="_blank" href="https://scrappedscript.com/series/bit-by-bit">Bit by Bit</a>, a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</p>
<p>New articles in this series are posted every Tuesday!</p>
<hr />
<h2 id="heading-i-overview-of-flow-state">I. Overview of flow state</h2>
<p><img src="https://images.unsplash.com/photo-1504221507732-5246c045949b?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="fluid art" class="image--center mx-auto" /></p>
<p>Imagine this: you sit down to program and the entire world melts away. Suddenly, all of your worries and fears vanish. The only thing that exists is your mind and the computer in front of you.</p>
<p>Any prior feelings of fatigue, hunger, thirst, and discomfort are no longer there.</p>
<p>Your eyes are locked onto the code editor with razor-sharp focus. Your fingers seem to be typing as fast as your thoughts.</p>
<p>You're effortlessly generating ingenious solutions and executing those solutions with such elegant code.</p>
<p>Anytime you run your code and get an error, you're able to debug with such grace as if the error is just some dust that you're wiping off with a microfiber cloth.</p>
<p>This is exactly what being in a flow state feels like.</p>
<p>The flow state is a term from the field of psychology that describes the feeling that people get when they're fully immersed in a task/activity. The activities that are associated with this state are individual to every person but are typically activities that a person is passionate about and skilled at.</p>
<h3 id="heading-a-effects-of-achieving-a-flow-state">a) Effects of achieving a flow state</h3>
<p>Some of the common effects that people report when they enter a flow state include:</p>
<ul>
<li><p>Intense focus</p>
<ul>
<li><p>It's very hard to get distracted while you're in a flow state</p>
</li>
<li><p>You might get a little irritated if someone tries to get your attention while you're in a flow state</p>
</li>
</ul>
</li>
<li><p>Reduced stress/anxiety</p>
<ul>
<li><p>Being in a flow state can make you feel very calm without feeling sedated</p>
</li>
<li><p>A flow state can make you even more productive than a cup of coffee can but without any of the negative effects (jitters, anxiety, etc.)</p>
</li>
</ul>
</li>
<li><p>Increased self-esteem/confidence</p>
<ul>
<li><p>When you're in a flow state, you feel like an absolute expert in the activity that you're engaging with</p>
</li>
<li><p>You have no self-doubt about your capabilities</p>
</li>
</ul>
</li>
<li><p>An intense feeling of joy</p>
</li>
<li><p>Enhanced creativity and problem-solving skills</p>
</li>
</ul>
<p>I've entered into a flow state numerous times while programming or solving math problems in coursework and I've experienced all of those wonderful effects that I described above.</p>
<p>Typically, a flow state for me can last anywhere from a couple of hours to the entire day. In the cases where I was in a flow state the entire day, I wouldn't even take breaks to eat or socialize (unless I was working alongside one or more people).</p>
<p>Although, on days where I was in a flow state the entire day, I'd sometimes take 15-30 minute walks to draw inspiration from music (usually Kanye West :D ) and get a little mid-day exercise in.</p>
<iframe id="embedPlayer" src="https://embed.music.apple.com/us/playlist/highsnobietys-40-best-kanye-west-songs/pl.cd6cbb57ac9548a99d5fc83eddc5a479?app=music&amp;itsct=music_box_player&amp;itscg=30200&amp;at=1000l3bi6&amp;ls=1&amp;theme=dark" height="450px" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation-by-user-activation" style="width:100%;max-width:660px;overflow:hidden;border-radius:10px;transform:translateZ(0px);animation:2s ease 0s 6 normal none running loading-indicator;background-color:rgb(228, 228, 228)"></iframe>

<p><a target="_blank" href="https://music.apple.com/us/playlist/highsnobietys-40-best-kanye-west-songs/pl.cd6cbb57ac9548a99d5fc83eddc5a479?itsct=music_box_link&amp;itscg=30200&amp;at=1000l3bi6&amp;ls=1&amp;app=music"><img src="https://tools.applemediaservices.com/api/badges/listen-on-apple-music/badge/en-us?size=250x83" alt="apple music badge" /></a></p>
<p>Even during these walks, I would still feel all of those effects of being in a flow state and my mind would continue to conjure up solutions related to the activity that I was engaged with.</p>
<hr />
<h2 id="heading-ii-factors-influencing-the-flow-state">II. Factors influencing the flow state</h2>
<p><img src="https://images.unsplash.com/photo-1599501151629-bc4f16c447ce?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="person playing the keyboard" class="image--center mx-auto" /></p>
<p>The greatest thing about the flow state is that everyone can organically enter this state.</p>
<p>With that being said, certain factors at play influence whether you can successfully enter a flow state for the task that you're engaged in.</p>
<h3 id="heading-a-skill-level">a) Skill level</h3>
<p>Perhaps one of the most important factors for entering a flow state is how skilled you are at that particular task/activity.</p>
<p>If you're a programmer, this doesn't mean you have to be on the same level as Guido van Rossum (the creator of Python). It just means that you should already have a solid foundation.</p>
<p>If you're just starting to learn how to program, for example, then it's much harder to enter into a flow state.</p>
<p>Alternatively, if you're past the learning curve and now able to build cohesive programs, then you might find it easier to enter a flow state.</p>
<p>I think it's worth noting that this doesn't necessarily mean that you can't feel generally focused and rewarded during the learning process. As long as you're passionate about software engineering, then the learning process won't feel dull.</p>
<p>It's just that you won't be able to reach that specific feeling of being in a flow state while you're still learning.</p>
<h3 id="heading-b-challenge-level">b) Challenge level</h3>
<p>The challenge level of the activity is a factor that goes hand-in-hand with your skill level associated with the activity.</p>
<p>If a task is too easy, then you'll just end up feeling bored and unsatisfied.</p>
<p>But if the task is fairly challenging, then it'll be much easier to enter a flow state.</p>
<p>Once you're able to combine your high skill level with a challenging task, you'll become unstoppable.</p>
<h3 id="heading-c-environment">c) Environment</h3>
<p>The environment you're in while you're doing the activity is a highly individual factor for inducing a flow state.</p>
<p>What might work for someone else may not work for you.</p>
<p>I know that the perfect environment for me to enter a flow state is at nighttime at a coffee shop with a low level of distractions and surrounded by other busy people.</p>
<p>If you've never experienced a flow state, start by asking yourself where you're usually the most productive.</p>
<p>Think about the noise level, whether you're alone or around others, in public or private, the time of day, and even the weather. Obviously, you can't control the weather, but if you find that you're more productive on rainy days, for example, maybe try simulating that by playing the sound of rain and getting a hot drink (if you do that on rainy days). If you notice that you're more productive when it's warm and sunny, then maybe try doing the activity in a bright location.</p>
<h3 id="heading-d-mindset">d) Mindset</h3>
<p>Similar to the environment, your mindset is another highly individual factor.</p>
<p>A positive, or at least neutral, mindset is conducive to entering a flow state.</p>
<p>If your mind is too focused on negative thoughts before engaging in the activity, then it'll be hard to enter a flow state.</p>
<p>In my own experience, it's also the context of the thoughts that matter as well. If my mind is occupied by stressors and anxiety that are completely irrelevant to the activity, then it's almost impossible to enter a flow state.</p>
<p>Although, it's possible for me to still enter a flow state if I have negative thinking that's directly related to the activity.</p>
<p>For example, if I'm pressed by a deadline, then I find that this doesn't prevent me from entering a flow state. Further, the flow state will even completely override the stress of the deadline.</p>
<hr />
<h2 id="heading-iii-techniques-to-enter-flow-state">III. Techniques to enter flow state</h2>
<p><img src="https://images.unsplash.com/photo-1619468610762-db5d88df3e9d?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1473&amp;q=80" alt="programmer sitting at laptop and coding" class="image--center mx-auto" /></p>
<p>Now that you understand the main factors that go into entering a flow state, you can learn specific ways to enter into a flow state.</p>
<p>Sometimes, you might notice that you "accidentally" enter into a flow state without even trying. However, there are tricks you can do to purposely enter into a flow state (assuming you have all those main factors covered).</p>
<h3 id="heading-a-set-clear-goals">a) Set clear goals</h3>
<p>Being in a flow state is naturally very productive and goal-driven.</p>
<p>So it makes sense that one of the steps you should take to enter a flow state is to know exactly what you want to accomplish.</p>
<p>If you have a clear roadmap, then you'll be able to gauge your progress and clear all the confusion revolving around the path you need to take. With all the confusion out of the way, your mind has more room to focus on the actual activity.</p>
<p>In software engineering, this can very easily be accomplished by doing things like flowcharts and pseudocode before writing code.</p>
<h3 id="heading-b-eliminate-distractions">b) Eliminate distractions</h3>
<p>To enter this immense state of focus, you'll first need to clear any distractions that are demanding your attention.</p>
<p>This means to get rid of anything that is not directly related to the activity/task you're about to do.</p>
<p>If you're programming, this means putting away your phone, putting your code editor into full-screen mode, and not talking to anyone about anything unless it's about that specific program you're working on.</p>
<h3 id="heading-c-create-a-dedicated-workspace">c) Create a dedicated workspace</h3>
<p>This tip does not have so much to do with the actual space around you (I had already discussed the environmental factor above). Rather, I'm referring to the tools and resources you interact with during your activity.</p>
<p>For example, when I'm programming, I always use the same laptop, the same code editor(s), the same color theme, and even the same code editor layout (I like keeping a terminal open in the bottom panel of the code editor ;)</p>
<p>Figure out what works best for you and stick with it.</p>
<h3 id="heading-d-balance-skill-and-challenge">d) Balance skill and challenge</h3>
<p>As I mentioned above in the main factors, you want the activity to be challenging and stimulating, and you want to be skilled in the work related to the activity.</p>
<p>However, don't overestimate your abilities, otherwise, you'll just end up getting frustrated.</p>
<p>For example, if you're engineering a game and you reach a point where you need to use a new library/framework to achieve the next step you need to do, then take the necessary time to study and learn about the library/framework.</p>
<p>Make sure that you're knowledgeable enough about the tools required for an activity before attempting to enter into a flow state.</p>
<h3 id="heading-e-practice-mindfulness">e) Practice mindfulness</h3>
<p>Start practicing mindful meditation!</p>
<p>Mindful meditation is the practice of closing your eyes, relaxing all of your muscles, and centering all of your attention and focus on your breath.</p>
<p>A lot of the ideas and feelings around the flow state are related to the same state that a human can reach while in a mindful meditative state.</p>
<p>The key difference between mindful meditation and a flow state is that mindful meditation does not involve engaging with a task (besides meditating).</p>
<p>Not only can mindful meditation open you up to the feeling of a flow state, but it can also make it easier to integrate mindfulness into every aspect of your life.</p>
<p>Understanding how to be mindful will make it much easier to naturally enter into a flow state.</p>
<h3 id="heading-f-meditation-techniques">f) Meditation techniques</h3>
<p>Mindful meditation is only one type of meditation. Another powerful meditation technique is transcendental meditation.</p>
<p>Transcendental meditation is a completely silent meditation practice where you close your eyes, clear your mind, and silently repeat a mantra in your head. A mantra is usually a one or two-syllable <strong>sound</strong> that holds no sentimental meaning to you.</p>
<p>It's considered best to practice transcendental meditation twice a day for 20 minutes each time if you want to reap the benefits. Also, you should choose one mantra that you'll use every single time.</p>
<p>While transcendental meditation is very simple, it can be hard if you're completely new to meditation.</p>
<p>Unlike mindful meditation, transcendental meditation has nothing to do with focus and attention. Instead, <a target="_blank" href="https://www.bmedreport.com/archives/10222">transcendental meditation is about entering a "restful-alert"</a> state where you're awake but your mind is not in a fully conscious state. Instead, your mind is in what's called "default mode". If you're curious to learn more about how transcendental meditation affects the brain, I left a link to an EEG study that analyzes brain activity during transcendental states.</p>
<p>Even though transcendental meditation isn't focus-based, it can lead to enhanced creativity and a calmer resting state throughout the day, which are both things that are conducive to entering a flow state.</p>
<h3 id="heading-g-dont-force-it">g) Don't force it</h3>
<p>Lastly, don't rush the process.</p>
<p>One of the worst things you can do when trying to enter a flow state is to try to force it and become frustrated that you're not getting there.</p>
<p>Be patient with yourself and allow it to come to you.</p>
<hr />
<h2 id="heading-iv-enhancing-creativity-in-a-flow-state">IV. Enhancing creativity in a flow state</h2>
<p><img src="https://images.unsplash.com/photo-1603302576837-37561b2e2302?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1468&amp;q=80" alt="laptop halfway closed with screensaver background" class="image--center mx-auto" /></p>
<p>Now that you understand how to generally enter into a flow state, you can learn how to maximize the benefits of the flow state to achieve the task at hand.</p>
<h3 id="heading-a-encourage-exploration">a) Encourage exploration</h3>
<p>Don't be afraid to explore new ways of doing things, new perspectives, and fresh insights from other people.</p>
<p>If you stay stuck believing that your way is the only way or the perfect way, then you'll never even have the possibility of discovering a more efficient or creative method.</p>
<p>For example, if you casually stumble upon an article or video explaining a method of accomplishing some programming task, then don't be afraid to implement that method into the program you're currently working on.</p>
<p>I can't tell you how many times I've refactored my code the very next day after realizing that there's a more elegant way to accomplish the task, or a more efficient method that saves compute time and power.</p>
<h3 id="heading-b-experiment-with-different-programming-techniques">b) Experiment with different programming techniques</h3>
<p>This is similar to my last point, but try techniques that you've never used before.</p>
<p>For instance, if you always define subarrays with loops, then try switching it up by using set comprehensions.</p>
<p>Oftentimes, making even small changes in habits (albeit, that example habit isn't inherently <em>bad</em>) like this can potentially lead to new insights in problem-solving.</p>
<h3 id="heading-c-seek-inspiration-from-various-sources">c) Seek inspiration from various sources</h3>
<p>Finally, find a good set of people that inspire and motivate you.</p>
<p>These people don't even necessarily have to be involved in the type of work you're doing.</p>
<p>When you find at least a few people who strike the right chord with you, then you'll naturally find it much easier to have hope and be more positive in general.</p>
<p>For me, I find that Kanye's music greatly inspires and motivates me, so it was very effective for me to listen to his music while taking short walks on days when I was in a flow state.</p>
<p>Find artists, scientists, leaders, etc. that boost your motivation and make you feel captivated; then find ways to consistently be reminded of their work.</p>
<hr />
<h2 id="heading-v-conclusion">V. Conclusion</h2>
<p>I hope that you now have a better understanding of what the flow state exactly is and how to enter into a flow state to effectively accomplish your goals.</p>
<p>Remember to stay patient with yourself and take the time necessary to build up the skills and knowledge required for the activity/task you're going to embark on.</p>
<p>If you have any questions or suggestions for a topic you want me to cover in the future, then feel free to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
<hr />
<h2 id="heading-vi-additional-resources">VI. Additional resources</h2>
<h3 id="heading-a-articles">a) Articles</h3>
<ul>
<li><a target="_blank" href="https://www.bmedreport.com/archives/10222">A New EEG Study Finds That Transcendental Meditation Activates The Default Mode Network Of The Brain (2010)</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Intro to Discrete Math: How to Logically Prove Arguments]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases. Read the full disclosure

In this article, we explore the basics of logic in discrete mathematics, c...]]></description><link>https://scrappedscript.com/intro-to-discrete-math-how-to-logically-prove-arguments</link><guid isPermaLink="true">https://scrappedscript.com/intro-to-discrete-math-how-to-logically-prove-arguments</guid><category><![CDATA[discrete mathematics]]></category><category><![CDATA[logic]]></category><category><![CDATA[Mathematics]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Thu, 12 Oct 2023 17:42:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/h1ShPXfHbTw/upload/45dd8a167011dbf75518a670b9dce3f1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.</em> <a target="_blank" href="https://scrappedscript.com/disclaimers"><strong>Read the full disclosure</strong></a></p>
<blockquote>
<p>In this article, we explore the basics of logic in discrete mathematics, covering propositional variables, logical connectives/operators, truth tables, tautologies, contradictions, logical equivalence, and forming inverses, converses, and contrapositives of base implications. By understanding these concepts, you can build a strong foundation for further study in discrete math and its applications in computer science.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://images.unsplash.com/photo-1596496181871-9681eacf9764?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1486&amp;q=80" alt="a woman writing on a whiteboard with a marker" class="image--center mx-auto" /></p>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/log-base-two"><strong>Log Base Two</strong></a><strong>", a series dedicated to the relationship between math and computer science</strong>.</p>
<p>Just to give a bit of background on my experience in math, I've <strong>excelled</strong> in a total of 10 college courses in math:</p>
<ol>
<li><p><strong>Single-variable differential calculus</strong></p>
</li>
<li><p><strong>Single-variable integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus of vector-valued functions</strong></p>
</li>
<li><p><strong>Linear Algebra</strong></p>
</li>
<li><p><strong>Differential equations</strong></p>
</li>
<li><p><strong>Probability and statistics</strong></p>
</li>
<li><p><strong>Data analysis using R programming language</strong></p>
</li>
<li><p><strong>Multivariate statistics</strong></p>
</li>
<li><p><strong>Discrete math</strong></p>
</li>
</ol>
<p>For a large majority of those 10 classes, I ended up with A's.</p>
<p>Although, before college, I struggled a lot with math in the classroom, even though math had always been my favorite subject since I was in elementary school. I found it hard to truly grasp the concepts taught because my high school teachers were too focused on skill assessment. Instead of focusing on the actual concept being taught, I was too worried about how I was going to pass the test the following week.</p>
<p>Once I got to college, I realized that your math grade (or any grade for that matter) truly doesn't define your potential. Further, I'd argue that your success in math <em>education</em> is heavily influenced by the quality of the teacher/professor's teaching.</p>
<p>My mission with this series is to show other people that math isn't so scary if you break down mathematical concepts into digestible bouts of information and investigate use cases of math in your primary field of interest (in this case, computer science). Along the way, I hope to also supplement your math education with quality content. I believe that <strong>everyone</strong> is capable of learning and truly loving mathematics.</p>
<p><strong>New articles in this series are posted every Thursday!</strong></p>
<hr />
<h2 id="heading-amazon-prime-free-trial">Amazon Prime Free Trial</h2>
<p><a target="_blank" href="https://amzn.to/3QfXqGJ"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<p><strong>Free 30-day trial for Amazon Prime:</strong> <a target="_blank" href="https://amzn.to/3RJN4zV">https://amzn.to/3RJN4zV</a></p>
<p><a target="_blank" href="https://amzn.to/3tsi8d7"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696024499520/2a95658c-353a-4083-afba-1b1bc89b358f.jpeg?auto=compress,format&amp;format=webp" alt="a woman holding a box with amazon prime on it" class="image--center mx-auto" /></a></p>
<p><em>For college students</em>; <strong>Free 6-month trial for Amazon Prime Student</strong>: <a target="_blank" href="https://amzn.to/45mPuHV">https://amzn.to/45mPuHV</a></p>
<hr />
<h2 id="heading-i-overview-of-logic">I. Overview of logic</h2>
<p><img src="https://images.unsplash.com/photo-1580894736036-7a68513983ec?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="two women standing in front of a white board" class="image--center mx-auto" /></p>
<p>Our ability to reason using logic is perhaps one of the most defining qualities of what makes us human.</p>
<p>Even when we're being "overly emotional", we're technically still using logic. Albeit, this type of logic is usually based on fallacies.</p>
<p>For instance, if you choose to never visit a restaurant again because you got food poisoning from it once, you're using logic based on your personal experience of the painful torment you had to endure that will forever be tied to that restaurant in your mind.</p>
<p>Alternatively, if you got food poisoning from a restaurant once but choose to keep dining at the restaurant, maybe your logical defense is that you've eaten at the restaurant hundreds of times so that one time is not statistically significant.</p>
<p>In both of those cases of reasoning, you're forming an argument constructed from a logical relationship between 2 propositions.</p>
<p>In the first case, your root, refined argument is: "<em>If I get food poisoning from a restaurant, then I'll get food poisoning from the restaurant again.</em>" The first proposition is "<em>If I get food poisoning from a restaurant</em>", and the second proposition is "<em>I'll get food poisoning from the restaurant again</em>". You then logically construct your argument by connecting these 2 propositions with an "if...then" statement. Whether this argument is true or not is another story.</p>
<p>In the second case, your root, refined argument is: "<em>If I get food poisoning from a restaurant less than 1% of the hundreds of times I've eaten there, then it is due to random chance.</em>" The first proposition is "<em>If I get food poisoning from a restaurant less than 1% of the hundreds of times I've eaten there</em>", and the second proposition is "<em>It is due to random chance</em>". Once again, you connect these 2 propositions using an "if...then" statement to form your argument.</p>
<p>At this point, it should be noted that sometimes, certain arguments can be incredibly hard to prove or disprove, and sometimes even <strong>impossible</strong> to prove or disprove.</p>
<p>For the first argument to be true, all that has to happen is you get food poisoning from the restaurant at least once more. Theoretically, you could get food poisoning from the restaurant again the very next month and conclusively prove your argument true. Alternatively, for the first argument to be false, you'd have to never get food poisoning from the restaurant again in your life. Although, assuming you live for a long time, it could take decades before this argument can conclusively be proven false.</p>
<p>On the other hand, the second argument is very hard to prove true or false from the get-go. This is because even if you never get food poisoning again from that restaurant, you can't definitively say that that one time was due to pure random chance. Perhaps you were unknowingly on a date with the chef's ex-significant other at the restaurant, and the jealous chef purposely spoiled your food.</p>
<p>While it may seem like I'm being unrealistic and overly cynical about this whole story above, there are even some cases in "pure" math where a particular argument can simply never be proven or disproven.</p>
<p>One of my favorite mathematicians of all time, Kurt Gödel, proved his "incompleteness theorems" showing that there can exist statements about/within a formal system that can't be proven or disproven and that the formal system itself can not prove that its own rules are logically consistent.</p>
<p>For instance, our second argument in our story about food poisoning might be true based on statistical <em>inference</em>, but as I stated, this doesn't mean that it can be <em>proven</em> true. Essentially, that argument is only as true as the statistical inference you're making, and that inference itself is based on conditions/rules that can't be proven to be logically consistent.</p>
<p>Now that you're mind is blown, let's break down the components of arguments and logical reasoning.</p>
<h3 id="heading-a-propositional-variables">a) Propositional variables</h3>
<p>In discrete math, we typically represent propositions as variables for convenience.</p>
<p>Usually, the standard variables used for an argument with 2 propositions are <em>P</em> and <em>Q.</em></p>
<p>For example, for the first argument in our food poisoning story, we'd define the propositions as:</p>
<p>$$P: If \ I \ get \ food \ poisoning \ from \ a \ restaurant$$</p><p>$$Q: I'll \ get \ food \ poisoning \ again$$</p><h3 id="heading-b-logical-operations-and-connectives">b) Logical operations and connectives</h3>
<p>The 5 rudimentary connectives/operators in propositional logic are:</p>
<ul>
<li>Implication (if...then)</li>
</ul>
<p>$$P \Rightarrow Q$$</p><ul>
<li>Bidirectional (if, and only if,...)</li>
</ul>
<p>$$P \Leftrightarrow Q$$</p><ul>
<li>Conjunction (and)</li>
</ul>
<p>$$P \land Q$$</p><ul>
<li>Disjunction (or)</li>
</ul>
<p>$$P \lor Q$$</p><ul>
<li>Negation (not)</li>
</ul>
<p>$$\lnot P$$</p><h3 id="heading-c-truth-tables">c) Truth tables</h3>
<p>To systematically and conveniently show that an argument is true, we use truth tables.</p>
<p>In a truth table, you essentially consider every possible case of an argument to logically show whether an argument is true or false.</p>
<p>For an argument with 2 propositions, there are 4 unique cases: both propositions are true, both propositions are false, only the first proposition is true, and only the second proposition is true.</p>
<p>Let's write out the basic truth tables for all 5 of those rudimentary connectives/operators.</p>
<p><strong>Implication</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td><em>Q</em></td><td><em>P</em> --&gt; <em>Q</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>As we see for an argument involving 2 propositions, an implication is only false when the first proposition is true but the second proposition is false.</p>
<p>Intuitively, this makes sense.</p>
<p>For instance, consider the following implication:</p>
<p>$$P: x = 2$$</p><p>$$Q: 3x = 5$$</p><p>$$P \Rightarrow Q$$</p><p>In this case, if <em>P</em> is taken as true, then we can assume that <em>Q</em> is false (since if x = 2, then 3x would equal 6). Therefore, our implication itself "If x = 2, then 3x = 5" is false.</p>
<p>One implication truth-value that might not make sense right away is how the implication "if <em>P</em> is false, then <em>Q</em> is true" is a true implication.</p>
<p>Consider the following implication:</p>
<p>$$P: It's \ always \ sunny \ outside$$</p><p>$$Q: The \ sun \ is \ always \ shining \ onto \ Earth$$</p><p>$$P \Rightarrow Q$$</p><p>Since there are sometimes clouds in the atmosphere, we can take <em>P</em> as sometimes false. Although, since the Earth is always in the path of the sun's light, we can take <em>Q</em> as always true. However, the implication itself "If it's always sunny outside, then the sun is always shining onto Earth" is true.</p>
<p><strong>Bidirectional</strong></p>
<p>To construct our bidirectional truth table, let's first think about what a bidirectional argument means in the context of implication.</p>
<p>In a bidirectional argument, we're essentially making an implication that works both ways.</p>
<p>Therefore, let's construct our bidirectional truth table with this in mind by making a column for "if <em>Q</em>, then <em>P</em>".</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td><em>Q</em></td><td><em>P</em> --&gt; <em>Q</em></td><td><em>Q</em> --&gt; <em>P</em></td><td><em>P</em> &lt;--&gt; <em>Q</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>True</td><td>True</td></tr>
</tbody>
</table>
</div><p>As we see for an argument involving 2 propositions, a bidirectional argument is only true when P and Q are logically equivalent (they have the same truth-vaues). So either <em>P</em> and <em>Q</em> are both true, or they're both false.</p>
<p>Consider the following bidirectional argument:</p>
<p>$$P: Penguins \ can \ fly$$</p><p>$$Q: All \ birds \ can \ fly$$</p><p>$$P \Leftrightarrow Q$$</p><p>Our argument is "Penguins can fly if, and only if, all birds can fly". As you may already know, penguins can't fly, therefore not all birds can fly (so both propositions are false). Although, the bidirectional argument itself "Penguins can fly if, and only if, all birds can fly" is true.</p>
<p><strong>Conjunction</strong></p>
<p>The other 3 connectives/operators are relatively straightforward.</p>
<p>Also, as a side note, these remaining 3 connectives/operators don't form complete arguments on their own but rather are used as components of an argument.</p>
<p>The conjunction of 2 propositions forms the statement "<em>P</em> and <em>Q</em>".</p>
<p>In terms of truth-value, a conjunction of 2 propositions is true if, and only if, both propositions are true. Therefore, if at least 1 of the propositions is false, then the conjunction is false.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td><em>Q</em></td><td><em>P</em> &amp; <em>Q</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>False</td></tr>
</tbody>
</table>
</div><p>Consider the following conjunction:</p>
<p>$$P: Monday \ comes \ before \ Tuesday$$</p><p>$$Q: Tuesday \ comes \ after \ Monday$$</p><p>$$P \land Q$$</p><p>Since both propositions are true on their own, the conjunction "Monday comes before Tuesday and Tuesday comes after Monday" is true.</p>
<p><strong>Disjunction</strong></p>
<p>The disjunction of 2 propositions forms the statement "<em>P</em> or <em>Q</em>".</p>
<p>In terms of truth-value, if at least 1 of the propositions is true, then the disjunction is true. Therefore, a disjunction of 2 propositions is false if, and only if, both of the propositions are false.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P or Q</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>False</td></tr>
</tbody>
</table>
</div><p>Consider the following disjunction:</p>
<p>$$P: I'm \ always \ right$$</p><p>$$Q: I'm \ sometime's \ wrong$$</p><p>$$P \lor Q$$</p><p>The first proposition is false, but the second proposition is true. Therefore, the disjunction "I'm always right or I'm sometimes wrong" is true.</p>
<p><strong>Negation</strong></p>
<p>The last logical operator we'll go over is negation.</p>
<p>Negation can operate on entire arguments, statements involving conjunctions or disjunctions, and even propositions themselves.</p>
<p>The negation of a proposition, argument, or statement is simply the opposite truth-value.</p>
<p>This means that if a proposition is true, then its negation is false. Alternatively, if a proposition is false, then its negation is true.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td>! <em>P</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>Consider the following negation:</p>
<p>$$P: Our \ solar \ system \ has \ 1 \ star$$</p><p>$$\lnot P$$</p><p>The proposition is true, therefore the negation "Our solar system does not have 1 star" is false.</p>
<h3 id="heading-d-tautologies">d) Tautologies</h3>
<p>A tautology is a logical statement or argument that is shown to always be true regardless of the truth values of the proposition(s).</p>
<p>There are plenty of examples of tautologies, but let's consider a simple tautology that involves only 1 proposition.</p>
<p>Using the operators we've covered, how do you think we might be able to form a tautology with only 1 proposition?</p>
<p>Since negation is the only operator that can be used on 1 proposition value, let's start with a negation truth table.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td>! <em>P</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>Since the negation is always the opposite value of the proposition, it'd be wise to next form a disjunction between <em>P</em> and ! <em>P.</em></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>! P</td><td>P or ! P</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td></tr>
</tbody>
</table>
</div><p>And voilà, we have a tautology:</p>
<p>$$P \lor \lnot P$$</p><p>Consider the following proposition:</p>
<p>$$P: I'm \ a \ billionaire$$</p><p>As an English statement, we have "I'm a billionaire or I'm not a billionaire". Logically, regardless of the truth value of the proposition, that statement is always true.</p>
<p>Let's now think of a tautology involving 2 propositions.</p>
<p>As we saw when we covered those 5 operators/connectives, the only 2 connectives that form logical statements that are true most of the time are implications and disjunctions (both of these connectives between two propositions result in a statement that is true 75% of the time).</p>
<p>Since we used a disjunction in the last example, let's try using an implication.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>That second implication case would be true if we had used a bidirectional connective instead of implication so let's include a bidirectional connective now.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td><td>(P --&gt; Q) &lt;--&gt; Q</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>False</td></tr>
</tbody>
</table>
</div><p>Now that the second case is true, the fourth case is false. Let's target that last case with a disjunction and negation.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td><td>(P --&gt; Q) &lt;--&gt; Q</td><td>(P --&gt; Q) &lt;--&gt; (Q or ! P)</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>And there you have it! We formed a tautology involving 2 propositions:</p>
<p>$$(P \Rightarrow Q) \Leftrightarrow (Q \lor \lnot P)$$</p><p>Consider the following propositions:</p>
<p>$$P: Pigs \ can \ fly$$</p><p>$$Q: Pigs \ are \ faster \ than \ airplanes$$</p><p>As an English statement, our tautology is "If pigs can fly, then pigs are faster than airplanes if, and only if, pigs are faster than airplanes or pigs can't fly". Regardless of whether those propositions are true or false on their own, that statement is always logically true.</p>
<p>As you can see, part of the fun of tautologies is that you can form completely absurd arguments that are always logically true.</p>
<h3 id="heading-e-contradictions">e) Contradictions</h3>
<p>Contrary to tautologies, we have contradictions. Contradictions are logical statements or arguments that are shown to always be false regardless of the truth-values of the propositions.</p>
<p>Similar to when we considered a tautology with only 1 proposition, let's try the same thing with a contradiction.</p>
<p>Let's start with just a simple negation again.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td>! <em>P</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td></tr>
</tbody>
</table>
</div><p>Since the negation of a proposition is always the opposite truth-value of the proposition, we can use a conjunction of the proposition and the proposition's negation.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td>! <em>P</em></td><td><em>P</em> &amp; ! <em>P</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>False</td></tr>
</tbody>
</table>
</div><p>And we now have our contradiction:</p>
<p>$$P \land \lnot P$$</p><p>Consider the following proposition:</p>
<p>$$P: I \ work \ for \ N.A.S.A.$$</p><p>We can then form the contradiction "I work for N.A.S.A. and I don't work for N.A.S.A.". Regardless of whether I work for N.A.S.A., this is a statement that is always logically false since both can't be true at the same time.</p>
<p>Let's now try forming a contradiction involving 2 propositions.</p>
<p>Since a conjunction of two propositions is only true 25% of the time, let's start with a conjunction of the first proposition and the second proposition's negation.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><em>P</em></td><td><em>Q</em></td><td><em>P</em> &amp; ! <em>Q</em></td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>False</td></tr>
<tr>
<td>True</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>False</td></tr>
</tbody>
</table>
</div><p>The only case that prevents our statement from being a contradiction is when the first proposition is true and the second proposition is false. If you remember, the truth-values of an implication between 2 propositions lead to the exact opposite results where the second case is the only case that's false and the rest of the cases are true. Because of this, we've found an important result: the negation of an implication between two propositions is logically equivalent to the conjunction of the first proposition with the second proposition's negation.</p>
<p>In math symbols:</p>
<p>$$\lnot (P \Rightarrow Q) \equiv (P \land \lnot Q)$$</p><p>As a side note, that symbol that looks like an equals sign with a third line is called a "logical equivalence" symbol.</p>
<p>Back to our contradiction, let's now add a disjunction between the first statement and the first proposition.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P &amp; ! Q</td><td>(P &amp; ! Q) or P</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>False</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>False</td><td>False</td></tr>
</tbody>
</table>
</div><p>If you notice, the truth values of our statement are logically equivalent to the first proposition's truth values.</p>
<p>$$(P \land \lnot Q) \lor P \equiv P$$</p><p>Using this fact, let's now form a conjunction between the statement we have and the negation of the first proposition.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P &amp; ! Q</td><td>(P &amp; ! Q) or P</td><td>((P &amp; ! Q) or P) &amp; ! P</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>False</td><td>True</td><td>False</td></tr>
<tr>
<td>True</td><td>False</td><td>True</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>False</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>False</td><td>False</td><td>False</td></tr>
</tbody>
</table>
</div><p>We've now arrived at a contradiction involving two propositions.</p>
<p>$$((P \land \lnot Q) \lor P) \land \lnot P$$</p><p>Consider the following propositions:</p>
<p>$$P: I \ live \ on \ Earth$$</p><p>$$Q: I'm \ a \ human$$</p><p>We can then form the contradiction "I live on Earth and I'm not a human, or I live on Earth. Also, I don't live on Earth". Regardless of whether these propositions are true, this statement will always be logically false.</p>
<h3 id="heading-f-logical-equivalence">f) Logical equivalence</h3>
<p>I briefly went over logical equivalence in the last section. Remember, if a statement/proposition has an identical truth table to another statement/proposition, then they are logically equivalent.</p>
<p>Although, this is not the only way to show logical equivalence.</p>
<p>Another method to show logical equivalence between two statements/propositions is if the bidirectional argument between them is a tautology.</p>
<p>Remember the tautology we made earlier?</p>
<p>$$(P \Rightarrow Q) \Leftrightarrow (Q \lor \lnot P)$$</p><p>Since this statement is both a tautology and a bidirectional argument between two substatements, the two substatements are logically equivalent.</p>
<p>In math symbols:</p>
<p>$$(P \Rightarrow Q) \equiv (Q \lor \lnot P)$$</p><p>Let's also review the example propositions we used:</p>
<p>$$P: Pigs \ can \ fly$$</p><p>$$Q: Pigs \ are \ faster \ than \ airplanes$$</p><p>The statement "If pigs can fly, then pigs are faster than airplanes" is logically equivalent to the statement "Pigs can't fly or pigs are faster than airplanes".</p>
<h3 id="heading-g-inverse-converse-and-contrapositive">g) Inverse, converse, and contrapositive</h3>
<p>For statements that are implications, we can form the inverse, converse, and contrapositive of that implication.</p>
<p>Let's start by defining our base implication:</p>
<p>$$P \Rightarrow Q$$</p><p>The inverse is then defined as:</p>
<p>$$\lnot P \Rightarrow \lnot Q$$</p><p>So if our base implication is the statement "If I study, then I'll do well on the test", then the inverse is the statement "If I don't study, then I won't do well on the test".</p>
<p>Let's analyze the truth table for these statements.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td><td>! P --&gt; ! Q</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>True</td></tr>
</tbody>
</table>
</div><p>Notice how if the inverse is false, then the base implication is true. This fact will come in handy when you prove math theorems.</p>
<p>Let's say you don't study for your test, yet you do well on the test. Then, you've disproven the inverse statement "If I don't study, then I won't do well on the test". By disproving that statement, you've automatically also <strong>proven</strong> the statement "If I study, then I'll do well on the test". Intuitively, this makes sense, as we're essentially saying that if we did well on the test without studying, then we would have for sure done well if we had studied.</p>
<p>Next, let's go over the converse.</p>
<p>The converse of our base implication is defined as:</p>
<p>$$Q \Rightarrow P$$</p><p>So if our base implication is "If I study, then I'll do well on the test", then the converse is "If I do well on the test, then I had studied".</p>
<p>Let's analyze the truth table.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td><td>Q --&gt; P</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>True</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>False</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>True</td></tr>
</tbody>
</table>
</div><p>If you notice, the truth table for the converse is the same as the truth table for the inverse, thus we've just shown that the inverse is logically equivalent to the converse.</p>
<p>$$(\lnot P \Rightarrow \lnot Q) \equiv (Q \Rightarrow P)$$</p><p>This also means that by proving the converse false, we consequently prove the base implication true. Once again, this fact will come in handy when you need to prove a math theorem.</p>
<p>Finally, let's cover the contrapositive.</p>
<p>The contrapositive of our base implication is defined as:</p>
<p>$$\lnot Q \Rightarrow \lnot P$$</p><p>So if our base implication is "If I study, then I'll do well on the test", then our contrapositive is "If I don't do well on the test, then I hadn't studied".</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>P</td><td>Q</td><td>P --&gt; Q</td><td>! Q --&gt; ! P</td></tr>
</thead>
<tbody>
<tr>
<td>True</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>True</td><td>False</td><td>False</td><td>False</td></tr>
<tr>
<td>False</td><td>True</td><td>True</td><td>True</td></tr>
<tr>
<td>False</td><td>False</td><td>True</td><td>True</td></tr>
</tbody>
</table>
</div><p>If you notice, the truth values for the contrapositive are the same as the base implication, thus the contrapositive is logically equivalent to the base implication.</p>
<p>$$(P \Rightarrow Q) \equiv (\lnot Q \Rightarrow \lnot P)$$</p><p>This means that if we prove the contrapositive to be true, then we consequently prove the base implication to be true.</p>
<p>So if you don't do well on the test and you hadn't studied for it, then you've proven the statement "If I don't do well on the test, then I hadn't studied" to be true. Consequently, you've also proven the statement "If I study, then I'll do well on the test" to be true.</p>
<hr />
<h2 id="heading-iii-conclusion">III. Conclusion</h2>
<p>I hope that this article has served as a starting ground for understanding the intricacies around logical statements in discrete math.</p>
<p>In this article, you learned about propositional variables, logical connectives/operators, truth tables, tautologies, contradictions, logical equivalence, and forming inverses, converses, and contrapositives of base implications.</p>
<p>The next topic to learn about in discrete math is how to apply everything you learned in this article to prove mathematical theorems. This might be a topic I cover in the future, so stay tuned ;)</p>
<p>If you have any lingering questions, then please make sure to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
]]></content:encoded></item><item><title><![CDATA[Beginner's Guide to Error Handling in Python]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases. Read the full disclosure

In this article, we discuss error handling in Python, including its import...]]></description><link>https://scrappedscript.com/beginners-guide-to-error-handling-in-python</link><guid isPermaLink="true">https://scrappedscript.com/beginners-guide-to-error-handling-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[error handling]]></category><category><![CDATA[exceptions]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 10 Oct 2023 19:51:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/bPVM4nOy0Rg/upload/b21095bbbfebba55200756fe9eb1937c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.</em> <a target="_blank" href="https://scrappedscript.com/disclaimers"><strong>Read the full disclosure</strong></a></p>
<blockquote>
<p>In this article, we discuss error handling in Python, including its importance in software development, how to work with exceptions and best practices for implementing error handling. We cover the use of try-except blocks, defining and raising custom exceptions, using additional clauses in the try-except block, and various tips for effective error handling.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress&amp;auto=compress,format&amp;format=webp" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a><strong>", a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</strong></p>
<p><strong>New articles in this series are posted every Tuesday!</strong></p>
<hr />
<h2 id="heading-amazon-free-trial">Amazon Free Trial</h2>
<p><a target="_blank" href="https://amzn.to/3RHIB0B"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<p><strong>Free 30-day trial for Amazon Prime:</strong> <a target="_blank" href="https://amzn.to/46do6NE">https://amzn.to/46do6NE</a></p>
<p><a target="_blank" href="https://amzn.to/46do9sO"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696024499520/2a95658c-353a-4083-afba-1b1bc89b358f.jpeg?auto=compress,format&amp;format=webp" alt="a woman holding a box with amazon prime on it" class="image--center mx-auto" /></a></p>
<p><em>For college students</em>; <strong>Free 6-month trial for Amazon Prime Student</strong>: <a target="_blank" href="https://amzn.to/3Q6ocBg">https://amzn.to/3Q6ocBg</a></p>
<hr />
<h2 id="heading-i-what-is-error-handling">I. What is error handling?</h2>
<p>Error handling is a systematic approach in programming that includes the anticipation, identification, and resolution of potential errors that may occur during the execution of a program.</p>
<p>On the most basic level, to effectively manage errors, programmers use methods such as including the use of error-handler blocks of code and the raising of exceptions in a program's code. This methodology not only prevents the program from crashing but also allows programmers to give some type of useful response in the form of an error message to the user.</p>
<hr />
<h2 id="heading-ii-overview-of-exceptions-in-python">II. Overview of exceptions in Python</h2>
<p>In Python, error handling involves utilizing try-except blocks to capture one or more exceptions or errors within a specific code segment in a program.</p>
<p>To catch an exception, you as the programmer have to specify which exception(s) to catch.</p>
<p>If you've already spent some time programming, you might've noticed that Python has a long list of predefined errors, including SyntaxError, NameError, TypeError, KeyError, AttributeError, and many more.</p>
<p>But what are these errors and where do they even come from?</p>
<p>As it turns out, just like everything else in Python, these predefined errors are just objects/classes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696543636803/e7d9d66a-043c-4e56-84b4-ac88dd2ef411.png" alt="Python idle" class="image--center mx-auto" /></p>
<p>With this in mind, let's take a quick analysis of what makes up these predefined exceptions in Python.</p>
<p>First, if you use Python's <code>dir</code> method, you can see all of the methods and parameters that are defined for <code>SyntaxError</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696543780449/9d21a2d7-8db9-4a1d-91e7-c161ca023cbf.png" alt="Python idle" class="image--center mx-auto" /></p>
<p>All of these methods and parameters work together to be able to reliably tell a programmer when they have a syntax error in their code.</p>
<p>As you can see below, when Python detects a syntax error, it automatically prints a message to the programmer: "SyntaxError: invalid syntax".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696543987030/013cfcc9-97b8-402c-9c97-c8c005dd7ebf.png" alt="Python idle" class="image--center mx-auto" /></p>
<h3 id="heading-b-defining-custom-exceptions-in-python">b) Defining custom exceptions in Python</h3>
<p>While it's amazing that the engineers behind Python are nice enough to include these predefined exceptions in Python's native software, what if there's a very specific error that could be encountered in your program and Python's long list of predefined exceptions don't automatically detect this particular error?</p>
<p>Well lucky for you, you can define your very own exceptions tailored to your program :D</p>
<p>Before you start coding away on defining an exception class, let's see if maybe all of these predefined exceptions in Python come from somewhere else (in other words, if they have a "superclass").</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696544663218/d56270d5-3600-4a3e-8140-35e36c657e17.png" alt="Python idle" class="image--center mx-auto" /></p>
<p>Sure enough, all of the predefined exceptions in Python inherit a base class structure from another class.</p>
<p>If you notice, KeyError's direct superclass is LookupError (which is just another type of exception), and LookupError's direct superclass is Exception. I included this example on purpose to show you that all of the predefined exceptions in Python ultimately inherit their base class structure from the Exception object/class.</p>
<p>With this in mind, we can use the same idea to quickly and conveniently define our own exceptions by inheriting the base structure from Python's Exception class and then adding in whatever custom functionality or attributes we want our specific exception to have.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Define custom exception's class and inherit</span>
<span class="hljs-comment"># attributes and methods from Exception class</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomError</span>(<span class="hljs-params">Exception</span>):</span>
    <span class="hljs-comment"># The pass keyword is just here as a placeholder</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>With the above code, keep in mind that the only "necessary" components are that you use the <code>class</code> keyword to define your exception as a class and that you inherit the Exception class by putting it in the parentheses after the class name (which can be named whatever you want, but it's best practice to follow the same syntactical style of Python's predefined exceptions by naming it a capitalized word followed by "Error").</p>
<p>And just to reiterate one of the comments I wrote in the code block, the <code>pass</code> keyword does nothing and is just there so that you don't get an error for leaving the <code>class</code> body empty.</p>
<hr />
<h2 id="heading-iii-overview-of-error-handling">III. Overview of error handling</h2>
<p>Now that we've covered what exceptions are, we can start learning how to work with exceptions in Python (aka, error handling).</p>
<p>The root of error handling in Python is using try-except blocks to "catch" exceptions.</p>
<p>The main idea is that by coding in unique error handling, we're either telling Python "I already know that this might give an error, and I want to handle the error in this way..." or we're telling Python "I want you to catch this potential, custom error from users, and I want to handle the error in this way...".</p>
<h3 id="heading-a-the-try-except-block">a) The try-except block</h3>
<p>The two necessary keywords in a try-except block are, unsurprisingly, <code>try</code> and <code>except</code>.</p>
<p>All of the code in the <code>try</code> section is technically run in Python but is not officially executed <strong>unless</strong> the code in the <code>try</code> section returns no error(s).</p>
<p>All of the code in the <code>except</code> section is <strong>only</strong> executed if the code in the <code>try</code> section returns an error.</p>
<p>You might be wondering why it's even worthwhile to catch Python's predefined exceptions. I mean, after all, it does seem redundant to catch an error that is already being caught by Python.</p>
<p>But in cases of catching Python's predefined exceptions, the usefulness lies in being able to customize the way the error is handled in the context of your program/software.</p>
<p>To illustrate this point, imagine you have a website that receives user requests for information about movies and all of the movie information is stored in your database on a server.</p>
<p>Let's say that this movie info is returned as JSON and is then converted to a dictionary in Python. In that case, if a user requests information about a movie that isn't listed in your database/dictionary, Python would return a KeyError (an error that's raised when you try returning a key's value for a key that doesn't exist).</p>
<p>Not only is this not really what's happening (the "real" error is that the movie isn't included in the database), but also this causes the program to crash.</p>
<p>This is a perfect example of a case where you should catch a predefined Python exception so that your program runs smoothly.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Dictionary of movie information</span>
movies = {
        <span class="hljs-string">"Annihilation"</span>: {
            <span class="hljs-string">"year"</span>: <span class="hljs-number">2018</span>,
            <span class="hljs-string">"director"</span>: <span class="hljs-string">"Alex Garland"</span>
        },
        <span class="hljs-string">"Ready Player One"</span>: {
            <span class="hljs-string">"year"</span>: <span class="hljs-number">2018</span>,
            <span class="hljs-string">"director"</span>: <span class="hljs-string">"Steven Spielberg"</span>
        },
        <span class="hljs-string">"Interstellar"</span>: {
            <span class="hljs-string">"year"</span>: <span class="hljs-number">2014</span>,
            <span class="hljs-string">"director"</span>: <span class="hljs-string">"Christopher Nolan"</span>
        } 
    }

<span class="hljs-keyword">try</span>:

    <span class="hljs-comment"># This line won't return an error</span>
    interstellar_info = movies[<span class="hljs-string">"Interstellar"</span>]

    <span class="hljs-comment"># This will return a KeyError since "Wall-E" isn't a key</span>
    <span class="hljs-comment"># in our dictionary</span>
    wall_e_info = movies[<span class="hljs-string">"Wall-E"</span>]

<span class="hljs-keyword">except</span> KeyError:

    print(<span class="hljs-string">"The movie you requested info for isn't listed in our database :("</span>)
</code></pre>
<p>When you execute the code above, you completely bypass Python's built-in KeyError handling/message, and instead, our custom message is what's returned. Most importantly, we're preventing the program from crashing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696553209668/c6317752-cb89-4ccb-964d-a59d2a0fdc3c.png" alt="terminal window" class="image--center mx-auto" /></p>
<h3 id="heading-b-catching-custom-exceptions">b) Catching custom exceptions</h3>
<p>Catching custom exceptions is the same process as catching predefined exceptions.</p>
<p>The only difference is that we have to first define our custom exception, as we had done earlier.</p>
<p>Additionally, we have to specify when our custom error is supposed to be raised.</p>
<p>I should note that generally, you probably won't need to define custom exceptions unless you're building some intricate software application. The reason for this is that for most general purposes, the if-else conditional statements do a good enough job of pivoting the output of a program for different use cases.</p>
<p>Although, I think it's still helpful to at least be exposed to the idea of being able to create/handle your own exceptions.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Define the custom exception</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomError</span>(<span class="hljs-params">Exception</span>):</span>

    <span class="hljs-keyword">pass</span>


<span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># Raise the custom exception</span>
    <span class="hljs-keyword">raise</span> CustomError

<span class="hljs-comment"># Handle the custom exception</span>
<span class="hljs-keyword">except</span> CustomError:

    print(<span class="hljs-string">"Custom error message"</span>)
</code></pre>
<p>One important thing I want to note about the code example above is that it's not necessary to place the <code>raise</code> keyword within the try-except block. You can raise your custom exception at any point in the program you feel is necessary.</p>
<p>The only reason I included it in the try-except block is to show a simple example of raising a custom exception.</p>
<h3 id="heading-c-catching-multiple-exceptions">c) Catching multiple exceptions</h3>
<p>In Python, you can handle multiple exceptions within one try-except block.</p>
<p>You simply do this by defining a tuple of which exceptions to handle.</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:

    <span class="hljs-keyword">raise</span> SyntaxError

<span class="hljs-keyword">except</span> (KeyError, SyntaxError):

    print(<span class="hljs-string">"Custom error message"</span>)
</code></pre>
<p>If you're trying to error-handle one particular part of your program that might cause more than one type of error, then this will come in handy.</p>
<h3 id="heading-d-the-else-clause">d) The else clause</h3>
<p>Try-except blocks have a couple of clauses that can be added but are not always necessary.</p>
<p>One of those clauses is the <code>else</code> clause. The <code>else</code> clause is only executed if there were no errors raised in the <code>try</code> section.</p>
<p>For example, if a user is trying to log in with two-factor authentication, then you'd first want to make sure that their credentials are correct when they attempt to log in before sending a code to their email/text.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserError</span>(<span class="hljs-params">Exception</span>):</span>

    <span class="hljs-keyword">pass</span>

my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"email@email.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">12345</span>
}

not_my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"mail@mail.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">123</span>
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_me_in</span>(<span class="hljs-params">user</span>):</span>

    <span class="hljs-keyword">if</span> user != my_account:

        <span class="hljs-keyword">raise</span> UserError

<span class="hljs-keyword">try</span>:

    <span class="hljs-comment"># This will raise UserError</span>
    log_me_in(not_my_account)

<span class="hljs-keyword">except</span> UserError:

    print(<span class="hljs-string">"Looks like you're not me!"</span>)

<span class="hljs-keyword">else</span>:

    print(<span class="hljs-string">"Welcome back! Enter the code we sent you"</span>)
</code></pre>
<p>When you execute the code above, the <code>else</code> clause won't execute, but the <code>except</code> clause will.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696556035043/b49aff91-7318-4131-9fbc-d3e57bc97d64.png" alt="terminal window" class="image--center mx-auto" /></p>
<p>Let's change the code to instead attempt to log me in instead.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserError</span>(<span class="hljs-params">Exception</span>):</span>

    <span class="hljs-keyword">pass</span>

my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"email@email.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">12345</span>
}

not_my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"mail@mail.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">123</span>
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_me_in</span>(<span class="hljs-params">user</span>):</span>

    <span class="hljs-keyword">if</span> user != my_account:

        <span class="hljs-keyword">raise</span> UserError

<span class="hljs-keyword">try</span>:

    <span class="hljs-comment"># This won't raise UserError</span>
    log_me_in(my_account)

<span class="hljs-keyword">except</span> UserError:

    print(<span class="hljs-string">"Looks like you're not me!"</span>)

<span class="hljs-keyword">else</span>:

    print(<span class="hljs-string">"Welcome back! Enter the code we sent you"</span>)
</code></pre>
<p>When we execute the code above, the UserError is not raised, so the <code>else</code> clause is then executed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696556152789/1f7837c9-c0fd-4a9b-88c0-a5a54a81b40a.png" alt="terminal window" class="image--center mx-auto" /></p>
<h3 id="heading-e-the-finally-clause">e) The finally clause</h3>
<p>The other clause that we can add to a try-except block is <code>finally</code>.</p>
<p>The <code>finally</code> section executes regardless of whether an error was raised.</p>
<p>This might be useful in a case where the program has to release a file that was submitted by a user.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserError</span>(<span class="hljs-params">Exception</span>):</span>

    <span class="hljs-keyword">pass</span>

my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"email@email.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">12345</span>
}

not_my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"mail@mail.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">123</span>
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_me_in</span>(<span class="hljs-params">user</span>):</span>

    <span class="hljs-keyword">if</span> user != my_account:

        <span class="hljs-keyword">raise</span> UserError

<span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># This will raise UserError</span>
    log_me_in(not_my_account)

<span class="hljs-keyword">except</span> UserError:
    <span class="hljs-comment"># This will execute</span>
    print(<span class="hljs-string">"Looks like you're not me!"</span>)

<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># This won't execute</span>
    print(<span class="hljs-string">"Welcome back! Enter the code we sent you"</span>)

<span class="hljs-keyword">finally</span>:
    <span class="hljs-comment"># This will execute</span>
    print(<span class="hljs-string">"No matter who you are, have a wonderful day!"</span>)
</code></pre>
<p>In the above code, even though UserError was raised, the <code>finally</code> section is executed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696556672254/0bfaa0f7-7428-4718-9852-96fb62db97c5.png" alt="terminal window" class="image--center mx-auto" /></p>
<p>Just to show you that the <code>finally</code> clause will also execute when there isn't a UserError, let's try logging in <code>my_account</code>.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserError</span>(<span class="hljs-params">Exception</span>):</span>

    <span class="hljs-keyword">pass</span>

my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"email@email.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">12345</span>
}

not_my_account = {
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"mail@mail.com"</span>,
    <span class="hljs-string">"password"</span>: <span class="hljs-number">123</span>
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_me_in</span>(<span class="hljs-params">user</span>):</span>

    <span class="hljs-keyword">if</span> user != my_account:

        <span class="hljs-keyword">raise</span> UserError

<span class="hljs-keyword">try</span>:

    log_me_in(my_account)

<span class="hljs-keyword">except</span> UserError:

    print(<span class="hljs-string">"Looks like you're not me!"</span>)

<span class="hljs-keyword">else</span>:

    print(<span class="hljs-string">"Welcome back! Enter the code we sent you"</span>)

<span class="hljs-keyword">finally</span>:

    print(<span class="hljs-string">"No matter who you are, have a wonderful day!"</span>)
</code></pre>
<p>After executing the code above, we see that the <code>finally</code> clause is still executed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696556850185/0420060f-7324-4784-9a46-e4d9a4b7f88f.png" alt="terminal window" class="image--center mx-auto" /></p>
<hr />
<h2 id="heading-v-best-practices-for-error-handling">V. Best practices for error handling</h2>
<p>Whenever you're implementing error handling into your code, there are certain things to pay attention to so that you truly reap the benefits of error handling.</p>
<h3 id="heading-a-catching-exceptions-as-specific-as-possible">a) Catching exceptions as specific as possible</h3>
<p>First, you want to make sure that you're not taking advantage of the fact that you can catch multiple exceptions at once.</p>
<p>Catching mutliple exceptions isn't a tool meant to overcome laziness per se, it's a tool to be able to handle a specific part of your program that might cause more than one type of error.</p>
<p>Additionally, you want to make sure that you're tailoring an error response specific to your program and the nature of the error.</p>
<h3 id="heading-b-graceful-degradation">b) Graceful degradation</h3>
<p>Finally, make sure that your program is always able to run smoothly.</p>
<p>I don't know anyone who enjoys the moment when an app crashes for apparently no reason.</p>
<p>One of the most noteworthy benefits of error handling is not only that you have control over what happens when an error occurs, but you also have the control to prevent the program from crashing!</p>
<p>If an error is raised and it's not properly handled, you risk damaging the functionality of the rest of the program and upsetting your users.</p>
<hr />
<h2 id="heading-vi-conclusion">VI. Conclusion</h2>
<p>I hope that you now have a better understanding of error handling in Python, and feel comfortable enough to start catching/handling errors and even defining/raising your own errors.</p>
<p>In this article, we went over the basic concept behind error handling, how to implement error handling in Python, how to define and raise custom exceptions, how to use additional clauses in the try-except block, and discussed some of the best practices when error handling.</p>
<p>Down below, I've linked some additional resources if you're interested in learning more about error handling in Python.</p>
<p>If you have any lingering questions or suggestions for a topic you want me to cover in the future, then please make sure to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
<hr />
<h2 id="heading-vii-additional-resources">VII. Additional resources</h2>
<h3 id="heading-a-amazon-prime-free-trial">a) Amazon Prime Free Trial</h3>
<p><a target="_blank" href="https://amzn.to/3tiK6Iy"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<p><strong>Free 30-day trial for Amazon Prime:</strong> <a target="_blank" href="https://amzn.to/3PLmWBT">https://amzn.to/3PLmWBT</a></p>
<p><a target="_blank" href="https://amzn.to/3rE6RWQ"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696051026485/dee0034b-2580-45a5-9ae5-7a51c5e06360.jpeg?auto=compress,format&amp;format=webp" alt="a woman holding a box with amazon prime on it" class="image--center mx-auto" /></a></p>
<p><em>For college students</em>; <strong>Free 6-month trial for Amazon Prime Student</strong>: <a target="_blank" href="https://amzn.to/45j4tT9">https://amzn.to/45j4tT9</a></p>
<h3 id="heading-b-videos">b) Videos</h3>
<p><a target="_blank" href="https://www.youtube.com/watch?v=ZsvftkbbrR0">Exception Handling Tips in Python</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=ZsvftkbbrR0">https://www.youtube.com/watch?v=ZsvftkbbrR0</a></div>
<p> </p>
<p>If you want to dive deeper into the concepts and techniques behind error handling, then I recommend checking out this video. Even if you're still a beginner, it might be beneficial to at least hear about some more advanced concepts so that you can start to think more creatively.</p>
<h3 id="heading-c-articles">c) Articles</h3>
<ul>
<li><p><a target="_blank" href="https://docs.python.org/3/tutorial/errors.html">Errors and Exceptions</a></p>
<ul>
<li>This is an all-inclusive tutorial straight from the official Python docs</li>
</ul>
</li>
<li><p><a target="_blank" href="https://realpython.com/python-raise-exception/">Python's raise: Effectively Raising Exceptions in Your Code</a></p>
<ul>
<li>I really like the way this author talks about when/how to use custom exceptions</li>
</ul>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Introduction to Binary and Hex in Computer Science]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases. Read the full disclosure

In this article, you will learn about the binary and hexadecimal number sy...]]></description><link>https://scrappedscript.com/introduction-to-binary-and-hex-in-computer-science</link><guid isPermaLink="true">https://scrappedscript.com/introduction-to-binary-and-hex-in-computer-science</guid><category><![CDATA[data]]></category><category><![CDATA[binary]]></category><category><![CDATA[hexadecimal]]></category><category><![CDATA[Computer Engineering]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Thu, 05 Oct 2023 15:36:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696020867764/ddf4e307-3fef-411f-9fd9-dd01e8a46576.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.</em> <a target="_blank" href="https://scrappedscript.com/disclaimers">Read the full disclosure</a></p>
<blockquote>
<p>In this article, you will learn about the binary and hexadecimal number systems, their importance in computer science, and how to convert between decimal, binary, and hexadecimal representations. You will also explore signed and unsigned integers, their conversion between different number systems, and their applications in computing. Additionally, this article includes helpful resources for further understanding these concepts and their practical use in computer science.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://images.unsplash.com/photo-1596496181871-9681eacf9764?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1486&amp;q=80" alt="a woman writing on a whiteboard with a marker" class="image--center mx-auto" /></p>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/log-base-two"><strong>Log Base Two</strong></a><strong>", a series dedicated to the relationship between math and computer science</strong>.</p>
<p>Just to give a bit of background on my experience in math, I've <strong>excelled</strong> in a total of 10 college courses in math:</p>
<ol>
<li><p><strong>Single-variable differential calculus</strong></p>
</li>
<li><p><strong>Single-variable integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus of vector-valued functions</strong></p>
</li>
<li><p><strong>Linear Algebra</strong></p>
</li>
<li><p><strong>Differential equations</strong></p>
</li>
<li><p><strong>Probability and statistics</strong></p>
</li>
<li><p><strong>Data analysis using R programming language</strong></p>
</li>
<li><p><strong>Multivariate statistics</strong></p>
</li>
<li><p><strong>Discrete math</strong></p>
</li>
</ol>
<p>For a large majority of those 10 classes, I ended up with A's.</p>
<p>Although, before college, I struggled a lot with math in the classroom, even though math had always been my favorite subject since I was in elementary school. I found it hard to truly grasp the concepts taught because my high school teachers were too focused on skill assessment. Instead of focusing on the actual concept being taught, I was too worried about how I was going to pass the test the following week.</p>
<p>Once I got to college, I realized that your math grade (or any grade for that matter) truly doesn't define your potential. Further, I'd argue that your success in math <em>education</em> is heavily influenced by the quality of the teacher/professor's teaching.</p>
<p>My mission with this series is to show other people that math isn't so scary if you break down mathematical concepts into digestible bouts of information and investigate use cases of math in your primary field of interest (in this case, computer science). Along the way, I hope to also supplement your math education with quality content. I believe that <strong>everyone</strong> is capable of learning and truly loving mathematics.</p>
<p><strong>New articles in this series are posted every Thursday!</strong></p>
<hr />
<h2 id="heading-amazon-prime-free-trial">Amazon Prime Free Trial</h2>
<p><a target="_blank" href="https://amzn.to/3tfl50P"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<p><strong>Free 30-day trial for Amazon Prime:</strong> <a target="_blank" href="https://amzn.to/458RWS5">https://amzn.to/458RWS5</a></p>
<p><a target="_blank" href="https://amzn.to/48BdnOu"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696024499520/2a95658c-353a-4083-afba-1b1bc89b358f.jpeg" alt="a woman holding a box with amazon prime on it" class="image--center mx-auto" /></a></p>
<p><em>For college students</em>; <strong>Free 6-month trial for Amazon Prime Student</strong>: <a target="_blank" href="https://amzn.to/3RGaKVD">https://amzn.to/3RGaKVD</a></p>
<hr />
<h2 id="heading-i-what-is-binary-and-hexadecimal">I. What is binary and hexadecimal?</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696024818690/bd99ab45-efea-49f2-a47c-16b0be1489c7.png" alt="a black and white image of 0s and 1s on a white background" class="image--center mx-auto" /></p>
<p>Our standard number system is the decimal system. The decimal system is <strong>base-10</strong>, meaning that every number in the decimal system is made from <strong>10 possible digits</strong> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).</p>
<p>The binary system and hexadecimal system are simply different number systems for counting and representing numbers.</p>
<p>Instead of base-10, the binary system is <strong>base-2</strong>, meaning that every number in the binary system is made from <strong>2 possible digits</strong> (0, 1).</p>
<p>On the other hand, the hexadecimal system is <strong>base-16</strong>, meaning that every number in the hexadecimal system is made from <strong>16 possible digits</strong> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).</p>
<h3 id="heading-a-importance-of-binary-and-hex-in-computer-science">a) Importance of binary and hex in computer science</h3>
<p>At the hardware level, computers use the binary system to represent data. Every single piece of data on a computer is encoded in binary including numbers, strings of text, images, and much more.</p>
<p>The reasoning behind the binary system being used to represent data in the CPU and RAM is to have a logical method of encoding information based on electrical signals.</p>
<p>The flow of electricity in a circuit has <em>two</em> possible states: flowing or not flowing. Think about a simple circuit for a light bulb; electricity is either flowing to the light bulb or it's not, thus the light is either on or it's off.</p>
<p>As you'll see in a bit, binary representations of data can become very lengthy due to the limited digit nature of binary. To compensate for this, the hexadecimal system is used to encode binary to make it easier for humans to work with large binary values.</p>
<hr />
<h2 id="heading-ii-binary-system">II. Binary system</h2>
<p><img src="https://images.unsplash.com/photo-1555589228-135c25ae8cf5?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="a close up of a computer circuit board" class="image--center mx-auto" /></p>
<p>One of the most important facts to consider in binary is that you start counting from 0.</p>
<p>The funny thing is that technically, the decimal system works the same way. Although, it's just not intuitive for humans to start counting from 0.</p>
<p>This is simply proven by the fact that the number 10 itself is represented with 2 distinct digits. The only way to count all the digits in the decimal system is to start at 0 and end at 9.</p>
<h3 id="heading-a-base-2-numeral-system">a) Base-2 numeral system</h3>
<p>One of the fundamental questions you might be asking is how you're supposed to count in binary.</p>
<p>And this question is completely valid. Since we have 10 fingers, it's subjectively very intuitive to count in the decimal system.</p>
<p>If you see a pile of 3 apples and start counting the apples by hand, you'd probably start with your index finger, then your middle finger, followed by your ring finger.</p>
<p>But what if you try counting a pile of 11 apples by hand? Luckily, we have a computer in our head that has memory, so we could simply count all our 10 fingers, then remember that we've already counted one full set of digits, and then just start counting again with a "fresh" set of digits.</p>
<p>More precisely, we start repeating digits. So we keep that "1" digit from the 10, and then use another "1" digit to represent 11 apples.</p>
<p>In binary, this is the same exact process that's used to count numbers.</p>
<p>Let's repeat the process of counting the pile of 3 apples with the binary system. Use only your index and middle finger to count, with your index finger representing the 0 digit and the middle finger representing the 1 digit.</p>
<p>Because we start counting at 0, we count the first apple as 0 with our index finger.</p>
<p>Next, we count the second apple by holding up both our index and middle finger (01).</p>
<p>Now that we've run out of digits, we place that 1 at the front and start repeating digits by retreating our index and middle fingers.</p>
<p>Finally, we count the third apple by holding up our index finger (the 0 digit), and our binary digit representation of our pile of 3 apples is <strong>10 (no, not 10 as in "ten", but 10 as in "one zero"</strong>.</p>
<p>If you do a quick search on Google to convert 10 in binary to the decimal system, you'll see that it equals 2.</p>
<p>Before you raise your pitchforks, remember what I said about how we start counting from 0 in binary, but traditionally start counting from 1 in the decimal system.</p>
<p>The main point to remember is that when we counted those 3 apples in binary, we counted through 3 numbers: 0, 01, 10.</p>
<h3 id="heading-b-binary-digits">b) Binary digits</h3>
<p>Another word for binary digits is <em>bits</em>.</p>
<p>In computing, a bit is considered the smallest quantity of information that can be processed or stored on a computer.</p>
<p>And yes, these are the same bits that are measured/converted in the metric system for quantifying data storage/memory.</p>
<p>As you may already intuitively know from maybe the storage capacity on your phone or laptop, we don't directly measure in bits, but in bytes.</p>
<p>8 bits = 1 byte.</p>
<p>1 gigabyte = 1,000,000,000 bytes = 8,000,000,000 bits.</p>
<p>1 terabyte =1,000 gigabytes = 1,000,000,000,000 bytes = 8,000,000,000,000 bits!</p>
<h3 id="heading-c-converting-from-decimal-integers-to-binary-digits">c) Converting from decimal integers to binary digits</h3>
<p>The algorithm to convert from decimal to binary is actually very simple.</p>
<p>The algorithm is to recursively divide the number in decimal by 2 and store (or write down if doing it by hand) the remainder after dividing, and then divide the whole number quotient by 2. This recursion stops once the quotient is 0.</p>
<p>After you finish dividing, string together all of the remainders starting with the last remainder (this is called the <em>most significant bit</em>, or MSB) and ending with the first remainder (this is called the <em>least significant bit</em>, or LSB).</p>
<p>Let's convert 24 in decimal to binary.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Dividend</td><td>Divisor</td><td>Quotient</td><td>Remainder</td></tr>
</thead>
<tbody>
<tr>
<td>24</td><td>2</td><td>12</td><td>0</td></tr>
<tr>
<td>12</td><td>2</td><td>6</td><td>0</td></tr>
<tr>
<td>6</td><td>2</td><td>3</td><td>0</td></tr>
<tr>
<td>3</td><td>2</td><td>1</td><td>1</td></tr>
<tr>
<td>1</td><td>2</td><td>0</td><td>1</td></tr>
</tbody>
</table>
</div><p>Since we reached a quotient of 0, we can now write out 24 in decimal to binary as <strong>11000</strong>.</p>
<h3 id="heading-d-bytes-and-padding">d) Bytes and padding</h3>
<p>Typically, bit representations are grouped into 8-bit groupings (1 byte).</p>
<p>This means that even if a number is less than 8 bits numerically, we still use 8 bits to represent the number.</p>
<p>This is accomplished with something called <em>padding</em>. Padding is the simple process of filling up a bit grouping with leading 0s until the grouping is 8-bit.</p>
<p>For our last example where we converted 24 to binary (<strong>11000</strong>), we only need 5 bits to represent 24 in binary.</p>
<p>To represent 24 in binary as a byte, we'd thus add 3 0s to the front of <strong>11000</strong>.</p>
<p>As a result, we get <strong>0001 1000</strong>. As a side note, it's not <em>necessary</em> to put a space in between 4 bits, but it does make it much easier to read in binary. Additionally, once we get to convert from binary to hex, you'll see why 4-bit groupings are advantageous.</p>
<h3 id="heading-e-signed-integers">e) Signed integers</h3>
<p>If our decimal number is negative, then the algorithm to convert to binary is slightly different.</p>
<p>Since the binary system doesn't inherently have positive and negative values, negative integers in the decimal system have to be encoded using a different algorithm so that negative decimal numbers have a unique binary representation, and thus have a unique path to be stored on a computer.</p>
<p>To convert a negative number in decimal to binary, you first convert the positive (unsigned) of that number to binary (in an 8-bit grouping representation). Once you have the unsigned (positive) binary number, you <em>invert</em> all of the bits (flip all of the 0s to 1s and vice-versa), then add 1 to the inverted, unsigned binary number. After you add 1, you now have the signed (negative) binary number.</p>
<p>Let's convert -24 in decimal to binary.</p>
<p>Since we already converted 24 to binary in the last example, we know that 24 is represented as <strong>0001 1000</strong> in binary.</p>
<p>Our next step is to invert <strong>0001 1000</strong>. After inverting, we get <strong>1110 0111</strong>.</p>
<p>Finally, we add 1 to the inverted binary number.</p>
<p>$$\begin{array}{c} &amp; 1110 &amp; 0111 \\ + &amp; 0000 &amp; 0001 \\ \hline &amp; 1110 &amp; 1000 \\ \end{array}$$</p><p>As a result, the binary representation for -24 is <strong>1110 1000</strong>.</p>
<p>As a side note, if you're confused about adding numbers in binary, remember back to earlier when you counted those 3 apples in binary. When you counted the second apple and represented the second apple as 01, you then counted the third apple by adding 1 to 01 by moving that "1" digit to the left.</p>
<p>Essentially, in binary:</p>
<ul>
<li><p>0 + 0 = 0</p>
</li>
<li><p>0 + 1 = 1</p>
</li>
<li><p>1 + 0 = 1</p>
</li>
<li><p>1 + 1 = 10</p>
</li>
</ul>
<p>So when I added those two numbers in the last example, I started with adding 1 + 1 to get 10, which means I put a 0 and "carried" over the 1 to the next column (1 + 0). Since 1 + 1 + 0 = 10, I again put 0 and "carried" over the 1.</p>
<h3 id="heading-f-converting-from-binary-digits-to-decimal-integers">f) Converting from binary digits to decimal integers</h3>
<p>Now that you know how to convert from decimal to binary, let's try the reverse.</p>
<p>To convert from unsigned binary numbers to decimal is pretty straightforward.</p>
<p>Each binary digit represents a decimal value, starting from 0 with the LSM and sequentially increasing by 1. To find the decimal value for that binary digit, you compute the result of that binary digit multiplied by 2 raised to the power of that digit's index in the sequence of bits.</p>
<p>Sounds very complicated in writing, but is very simple in math.</p>
<p>Let's try converting <strong>0001 1000</strong> to decimal.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Binary Digit</td><td>Index of Digit</td><td>Binary Digit * 2^Index of Digit</td></tr>
</thead>
<tbody>
<tr>
<td>0 (LSM)</td><td>0</td><td>0 * 2^0 = 0</td></tr>
<tr>
<td>0</td><td>1</td><td>0 * 2^1 = 0</td></tr>
<tr>
<td>0</td><td>2</td><td>0 * 2^2 = 0</td></tr>
<tr>
<td>1</td><td>3</td><td>1 * 2^3 = 8</td></tr>
<tr>
<td>1</td><td>4</td><td>1 * 2^4 = 16</td></tr>
<tr>
<td>0</td><td>5</td><td>0 * 2^5 = 0</td></tr>
<tr>
<td>0</td><td>6</td><td>0 * 2^6 = 0</td></tr>
<tr>
<td>0 (MSM)</td><td>7</td><td>0 * 2^7 = 0</td></tr>
<tr>
<td></td><td></td><td>Total = 24</td></tr>
</tbody>
</table>
</div><p>As a result, we see that <strong>0001 1000</strong> is the binary representation of 24 (which is consistent with when we converted 24 to binary).</p>
<p>As you might've guessed, converting signed negative integers in binary to decimal is a little different.</p>
<p>To start, you first invert the signed integer (flip the 0s to 1s and vice versa). Next, you add 1 to get the unsigned representation. Then, you convert the unsigned representation using the same algorithm in the last example. Finally, you make the resulting decimal integer negative.</p>
<p>Let's try it on <strong>1110</strong> <strong>1000</strong>.</p>
<p>First, we invert <strong>1110</strong> <strong>1000</strong> to <strong>0001</strong> <strong>0111</strong>.</p>
<p>Next, we add 1.</p>
<p>$$\begin{array}{c} &amp; 0001 &amp; 0111 \\ + &amp; 0000 &amp; 0001 \\ \hline &amp; 0001 &amp; 1000 \\ \end{array}$$</p><p>Then, we convert the unsigned representation to decimal using the method from the last example.</p>
<p>If you notice, <strong>0001</strong> <strong>1000</strong> is the same binary representation that we converted in the last example, and got 24.</p>
<p>Our last step is to then make 24 negative and get -24.</p>
<hr />
<h2 id="heading-iii-hexadecimal-system">III. Hexadecimal system</h2>
<p>Since binary data can be hard to read by humans, we invented the hexadecimal system to encode binary.</p>
<p>The hexadecimal system has 16 digits, and each digit represents a power of 16.</p>
<p>The first 10 digits of the hexadecimal system are identical to the standard decimal system (0-9). The other 6 digits are the first 6 letters in the alphabet (A-F).</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Decimal Number</td><td>Hexadecimal Digit</td></tr>
</thead>
<tbody>
<tr>
<td>0</td><td>0</td></tr>
<tr>
<td>1</td><td>1</td></tr>
<tr>
<td>2</td><td>2</td></tr>
<tr>
<td>3</td><td>3</td></tr>
<tr>
<td>4</td><td>4</td></tr>
<tr>
<td>5</td><td>5</td></tr>
<tr>
<td>6</td><td>6</td></tr>
<tr>
<td>7</td><td>7</td></tr>
<tr>
<td>8</td><td>8</td></tr>
<tr>
<td>9</td><td>9</td></tr>
<tr>
<td>10</td><td>A</td></tr>
<tr>
<td>11</td><td>B</td></tr>
<tr>
<td>12</td><td>C</td></tr>
<tr>
<td>13</td><td>D</td></tr>
<tr>
<td>14</td><td>E</td></tr>
<tr>
<td>15</td><td>F</td></tr>
</tbody>
</table>
</div><p>Since 1 hex digit represents 4 bits, we make sure to write hex representations in pairs of 2 to get 8-bit (byte) groupings of hex digits.</p>
<p>The process for doing so is the same as binary. We use padding by adding a leading 0 to the sequence of hex digits if the hex representation is an odd number of hex digits.</p>
<h3 id="heading-a-converting-from-decimal-integers-to-hex">a) Converting from decimal integers to hex</h3>
<p>The process of converting from decimal to unsigned hex is the same algorithm used to convert from decimal to binary, except instead of recursively dividing by 2, we divide by 16.</p>
<p>Let's try converting 1,932,345 to hex.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Dividend</td><td>Divisor</td><td>Quotient</td><td>Remainder</td></tr>
</thead>
<tbody>
<tr>
<td>1,932,345</td><td>16</td><td>120,771</td><td>9</td></tr>
<tr>
<td>120,771</td><td>16</td><td>7,548</td><td>3</td></tr>
<tr>
<td>7,548</td><td>16</td><td>471</td><td>12</td></tr>
<tr>
<td>471</td><td>16</td><td>29</td><td>7</td></tr>
<tr>
<td>29</td><td>16</td><td>1</td><td>13</td></tr>
<tr>
<td>1</td><td>16</td><td>0</td><td>1</td></tr>
</tbody>
</table>
</div><p>Our string of remainders is 1 13 7 12 3 9.</p>
<p>The next step is to convert any decimal remainder &gt; 9 to its hex digit.</p>
<p>As a result, our unsigned hex representation is <strong>1D7C39</strong>.</p>
<p>To represent a negative decimal integer in signed hexadecimal, the process is slightly different.</p>
<p>First, find the hex representation of the positive integer.</p>
<p>Next, subtract each digit from <strong>F.</strong></p>
<p>Finally, add 1.</p>
<p>Let's try converting -1,932,345 to hex.</p>
<p>From the previous example, we know the unsigned hex representation of 1,932,345 is <strong>1D7C39</strong>.</p>
<p>Our next step is to subtract <strong>F</strong> from each digit.</p>
<p>$$\begin{array}{c} &amp; \text{F} \text{F} \text{F} \text{F} \text{F} \text{F} \\ - &amp; 1 \text{D} 7 \text{C} 3 9 \\ \hline &amp; \text{E} 2 8 3 \text{C} 6 \\ \end{array}$$</p><p>Finally, add 1.</p>
<p>$$\begin{array}{c} &amp; \text{E} 2 8 3 \text{C} 6 \\ + &amp; 0 0 0 0 0 1 \\ \hline &amp; \text{E} 2 8 3 \text{C} 7 \\ \end{array}$$</p><p>Therefore, the signed hex representation of -1,932,345 is <strong>E283C7</strong>.</p>
<h3 id="heading-b-converting-from-hex-to-decimal-integers">b) Converting from hex to decimal integers</h3>
<p>The process of converting from unsigned hex to decimal is also the same process of converting unsigned binary to decimal, except instead of raising 2 to the power of the digit's index, we raise 16 to the power of the digit's index.</p>
<p>Let's try converting <strong>1D7C39</strong> to decimal.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Hex Digit</td><td>Index of Digit</td><td>Hex Digit * 16^Index of Digit</td></tr>
</thead>
<tbody>
<tr>
<td>9</td><td>0</td><td>9 * 16^0 = 9</td></tr>
<tr>
<td>3</td><td>1</td><td>3 * 16^1 = 48</td></tr>
<tr>
<td>C</td><td>2</td><td>12 * 16^2 = 3,072</td></tr>
<tr>
<td>7</td><td>3</td><td>7 * 16^3 = 28,672</td></tr>
<tr>
<td>D</td><td>4</td><td>13 * 16^4 = 851,968</td></tr>
<tr>
<td>1</td><td>5</td><td>1 * 16^5 = 1,048,576</td></tr>
<tr>
<td></td><td></td><td>Total = 1,932,345</td></tr>
</tbody>
</table>
</div><p>We end up getting that <strong>1D7C39</strong> is the hex representation for 1,932,345 (which is consistent with the example where we converted 1,932,345 to hex).</p>
<p>If you want to convert a signed hex value to decimal, you start by subtracting each digit from <strong>F</strong>.</p>
<p>Next, you add 1 to the result to get the unsigned representation.</p>
<p>Then, you convert the unsigned representation to decimal using the same algorithm used in the last example.</p>
<p>Finally, make the decimal value negative.</p>
<p>Let's try converting the signed hex representation of <strong>E283C7</strong> to decimal.</p>
<p>First, we'll subtract each digit from <strong>F</strong>.</p>
<p>$$\begin{array}{c} &amp; \text{F} \text{F} \text{F} \text{F} \text{F} \text{F} \\ - &amp; \text{E} 2 8 3 \text{C} 7 \\ \hline &amp; 1 \text{D} 7 \text{C} 3 8 \\ \end{array}$$</p><p>Next, we'll add 1 to get the unsigned hex representation.</p>
<p>$$\begin{array}{c} &amp; 1 \text{D} 7 \text{C} 3 8 \\ + &amp; 0 0 0 0 0 1 \\ \hline &amp; 1 \text{D} 7 \text{C} 3 9 \\ \end{array}$$</p><p>We already converted <strong>1D7C39</strong> to decimal in the last example to 1,932,345.</p>
<p>Therefore, we find that the signed hex representation of <strong>E283C7</strong> is -1,932,345 in decimal.</p>
<h3 id="heading-c-converting-from-binary-to-hex">c) Converting from binary to hex</h3>
<p>Converting from binary to hex is incredibly simple.</p>
<p>Let's do a bit of some combinatorics to find out how many unique combinations of 4-bit groupings there are.</p>
<p>First, for each digit in a 4-bit grouping, we have 2 choices (0 or 1).</p>
<p>$$\binom{2}{1} = \frac {2!} {1!(2-1)!} = \frac {2} {1} = 2$$</p><p>Second, to find the total amount of 4-bit combinations we can make, we take 2 raised to the power of 4 (since we have 4 digits in a group).</p>
<p>$$2^4 = 16$$</p><p>Therefore, we can make 16 possible 4-bit combinations.</p>
<p>Wait a minute, hexadecimal is base-16! :O</p>
<p>That's right, hexadecimal's design was no mistake; the inventors of hexadecimal not only wanted to simplify data representation for humans but also to conveniently be able to encode every single 4-bit grouping into a unique hex digit.</p>
<p>Here's a table showing every possible 4-bit combination encoded into a single, unique hex digit.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>4-bit Binary</td><td>Hexadecimal Digit</td></tr>
</thead>
<tbody>
<tr>
<td>0000</td><td>0</td></tr>
<tr>
<td>0001</td><td>1</td></tr>
<tr>
<td>0010</td><td>2</td></tr>
<tr>
<td>0011</td><td>3</td></tr>
<tr>
<td>0100</td><td>4</td></tr>
<tr>
<td>0101</td><td>5</td></tr>
<tr>
<td>0110</td><td>6</td></tr>
<tr>
<td>0111</td><td>7</td></tr>
<tr>
<td>1000</td><td>8</td></tr>
<tr>
<td>1001</td><td>9</td></tr>
<tr>
<td>1010</td><td>A</td></tr>
<tr>
<td>1011</td><td>B</td></tr>
<tr>
<td>1100</td><td>C</td></tr>
<tr>
<td>1101</td><td>D</td></tr>
<tr>
<td>1110</td><td>E</td></tr>
<tr>
<td>1111</td><td>F</td></tr>
</tbody>
</table>
</div><p>Let's try converting <strong>1010 1110 0010 1111 0001 1000</strong> to hexadecimal.</p>
<p>Using the table above, we find that the hexadecimal representation is <strong>AE2F18</strong>.</p>
<p>Simple, right?</p>
<h3 id="heading-d-converting-from-hex-to-binary">d) Converting from hex to binary</h3>
<p>Converting from hex to binary is the same process as converting binary to hex.</p>
<p>Except, instead of using the table to match a 4-bit grouping to a hex digit, you match a hex digit with a 4-bit grouping ;)</p>
<hr />
<h2 id="heading-iv-conclusion">IV. Conclusion</h2>
<p>In this article, you've learned about 2 different number systems (binary and hexadecimal) and how/why they're used in computing. Additionally, you've learned how to convert between decimal &lt;--&gt; binary, hexadecimal &lt;--&gt; binary, and decimal &lt;--&gt; hexadecimal.</p>
<p>I remember when I was brand new to the world of computer science, I was very confused about why the binary system was used, and why it was necessary to use hexadecimal. So I hope that I've explained binary and hex well enough to anyone new to computer science so that you don't have to be confused like I was at first.</p>
<p>I've also linked to some great resources below that I recommend checking out if you want to learn more about binary and hex.</p>
<p>If you have any lingering questions or suggestions for a topic you want me to cover in the future, then please make sure to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
<hr />
<h2 id="heading-v-additional-resources">V. Additional resources</h2>
<h3 id="heading-a-amazon-prime-free-trial">a) Amazon Prime Free Trial</h3>
<p><a target="_blank" href="https://amzn.to/3rDmDkz"><img src="https://m.media-amazon.com/images/G/01/pvc/PV1.jpeg" alt="a person holding a box with the amazon prime logo on it" class="image--center mx-auto" /></a></p>
<p><strong>Free 30-day trial for Amazon Prime:</strong> <a target="_blank" href="https://amzn.to/45a0ick">https://amzn.to/45a0ick</a></p>
<p><a target="_blank" href="https://amzn.to/3RJt40b"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696051026485/dee0034b-2580-45a5-9ae5-7a51c5e06360.jpeg" alt="a woman holding a box with amazon prime on it" class="image--center mx-auto" /></a></p>
<p><em>For college students</em>; <strong>Free 6-month trial for Amazon Prime Student</strong>: <a target="_blank" href="https://amzn.to/456TDQ9">https://amzn.to/456TDQ9</a></p>
<h3 id="heading-b-videos">b) Videos</h3>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=X8jsijhllIA">https://www.youtube.com/watch?v=X8jsijhllIA</a></div>
<p> </p>
<h3 id="heading-c-articles">c) Articles</h3>
<ul>
<li><p><a target="_blank" href="https://www.techtarget.com/whatis/definition/binary">What is binary and how is it used in computing?</a></p>
</li>
<li><p><a target="_blank" href="https://byjus.com/maths/binary-addition/">Binary Addition</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/hexadecimal-number-system/">The Hexadecimal Number System Explained</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Python Data Types Made Easy: A Comprehensive Guide]]></title><description><![CDATA[This article covers the basics of various data types in Python, including booleans, integers, floats, complex numbers, strings, lists, tuples, sets, and dictionaries. It provides an overview of each data type, along with examples of basic operations ...]]></description><link>https://scrappedscript.com/python-data-types-made-easy-a-comprehensive-guide</link><guid isPermaLink="true">https://scrappedscript.com/python-data-types-made-easy-a-comprehensive-guide</guid><category><![CDATA[Python]]></category><category><![CDATA[data structures]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 03 Oct 2023 15:50:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Nz0LoJB4d0g/upload/b3f004762a5b7f1db23537742ab867e7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>This article covers the basics of various data types in Python, including booleans, integers, floats, complex numbers, strings, lists, tuples, sets, and dictionaries. It provides an overview of each data type, along with examples of basic operations and functions that can be applied to them.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694158493008/jsZzIo77t.jpg?w=800&amp;auto=compress" alt="a person typing on a laptop on a desk" class="image--center mx-auto" /></p>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a><strong>", a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</strong></p>
<p><strong>New articles in this series are posted every Tuesday!</strong></p>
<hr />
<h2 id="heading-i-boolean-data-types">I. Boolean data types</h2>
<p><img src="https://images.unsplash.com/photo-1635241161466-541f065683ba?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1480&amp;q=80" alt="a white object on a blue background with a shadow" class="image--center mx-auto" /></p>
<p>Boolean data types serve as the fundamental building blocks of logic in programming.</p>
<p>Boolean data types play a critical role in many aspects of programming, including conditional statements, loops, and comparisons. They allow programmers to develop complex algorithms and control the flow of execution in their code, ultimately enabling the creation of sophisticated software applications that can adapt to various situations and user inputs.</p>
<h3 id="heading-a-true-and-false-values">a) True and false values</h3>
<p>Even when you're not directly declaring and storing variables with a boolean value, there's a good chance that you're using boolean values in the background of your programming.</p>
<p>With that being said, there are times when it's useful to declare and store variables with boolean values.</p>
<p>One small, but important, thing to note is that when using the True and False values in Python, make sure to capitalize the first letter of the words True and False.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Declare boolean variables</span>
a = <span class="hljs-literal">True</span>
b = <span class="hljs-literal">False</span>

<span class="hljs-comment">#basic operations</span>

<span class="hljs-comment">#and operation</span>
<span class="hljs-comment">#returns True if BOTH values are True</span>
and_value = a &amp; b
<span class="hljs-comment">#print(and_value) --&gt; False</span>

<span class="hljs-comment">#or operation</span>
<span class="hljs-comment">#returns True if at least one of the values is True</span>
or_value = a | b
<span class="hljs-comment">#print(or_value) --&gt; True</span>

<span class="hljs-comment">#is operation</span>
<span class="hljs-comment">#returns True if values are equal</span>
is_value = a == b
<span class="hljs-comment">#print(is_value) --&gt; False</span>

<span class="hljs-comment">#is not operation</span>
<span class="hljs-comment">#returns True if values are not equal</span>
is_not_value = a != b
<span class="hljs-comment">#print(is_not_value) --&gt; True</span>
</code></pre>
<hr />
<h2 id="heading-ii-numeric-data-types">II. Numeric data types</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695710899530/40fe6525-2fe3-4720-9880-129b3da02450.png" alt="a green button with white mathematical operators" class="image--center mx-auto" /></p>
<p>Numeric data types are among the most basic types of data. They are essential for performing calculations, designing algorithms, and developing intricate programs.</p>
<h3 id="heading-a-integers">a) Integers</h3>
<p>As you may recall from grade-school math, integers are a subset of the set of rational numbers where each integer is a number that can't be expressed as a ratio of two numbers except for itself and 1.</p>
<p>Integers can be positive or negative values, or zero, and are written without decimal points.</p>
<p>The main operations that are performed on integers in Python are arithmetic and comparison.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating integers</span>
x = <span class="hljs-number">5</span>
y = <span class="hljs-number">-3</span>

<span class="hljs-comment">#arithmetic operations</span>
<span class="hljs-comment">#addition</span>
total = x + y
<span class="hljs-comment">#print(total) --&gt; 2</span>

<span class="hljs-comment">#subtraction</span>
difference = x - y
<span class="hljs-comment">#print(difference) --&gt; 8</span>

<span class="hljs-comment">#multiplication</span>
product = x * y
<span class="hljs-comment">#print(product) --&gt; -15</span>

<span class="hljs-comment">#division</span>
quotient = x / y
<span class="hljs-comment">#print(quotient) --&gt; -1.6666666666666667</span>

<span class="hljs-comment">#modular division</span>
remainder = x % y
<span class="hljs-comment">#print(remainder) --&gt; -1</span>

<span class="hljs-comment">#floor division</span>
rounded_down_quotient = x // y
<span class="hljs-comment">#print(rounded_down_quotient) --&gt; -2</span>

<span class="hljs-comment">#exponentiation</span>
result = x ** y
<span class="hljs-comment">#print(result) --&gt; 0.008</span>

<span class="hljs-comment">#comparison operations</span>
<span class="hljs-comment">#greater than</span>
greater_than = x &gt; y
<span class="hljs-comment">#print(greater_than) --&gt; True</span>

<span class="hljs-comment">#less than</span>
less_than = x &lt; y
<span class="hljs-comment">#print(less_than) --&gt; False</span>

<span class="hljs-comment">#equal to</span>
equal_to = x == y
<span class="hljs-comment">#print(equal_to) --&gt; False</span>

<span class="hljs-comment">#not equal to</span>
not_equal_to = x != y
<span class="hljs-comment">#print(not_equal_to) --&gt; True</span>

<span class="hljs-comment">#greater than or equal to</span>
greater_or_equal = x &gt;= y
<span class="hljs-comment">#print(greater_or_equal) --&gt; True</span>

<span class="hljs-comment">#less than or equal to</span>
less_or_equal = x &lt;= y
<span class="hljs-comment">#print(less_or_equal) --&gt; False</span>
</code></pre>
<h3 id="heading-b-floats">b) Floats</h3>
<p>Floats, or floating-point integers, are any numbers written with a decimal point.</p>
<p>Technically speaking, a number that's formally defined as an integer in math can be stored as a <em>floating-point integer</em>.</p>
<p>For example, 6.00 is an integer in math, but since it has a decimal point it's stored as a floating-point integer in Python.</p>
<p>Floating-point integers and integers can have their values compared in Python. For example, when you use a comparison operator to check if 6.00 is equal to 6, Python returns True.</p>
<p>However, if you use a comparison operator to check if the data type of 6.00 is the same as the data type of 6, Python returns false.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696346135183/2ef6cc33-c4c9-487d-bf79-31eb773a9c79.png" alt="python idle code example" class="image--center mx-auto" /></p>
<p>Similar to integer data types, the main operations performed on floats are arithmetic and comparison.</p>
<p>As you might expect, you can apply all of those same operations in the integers code example I made with floating point values in Python.</p>
<h3 id="heading-c-complex-numbers-and-imaginary-numbers">c) Complex numbers and imaginary numbers</h3>
<p>For anyone in the field of quantum mechanics or electrical engineering, you're in luck ;)</p>
<p>In case you're unaware or need a quick refresher, complex numbers are 2-dimensional numbers where the first component is a real number and the second component is an imaginary number.</p>
<p>On the most basic level, imaginary numbers are expressed as a real number multiplied by the imaginary unit, <em>i</em>.</p>
<p>$$i = \sqrt{-1}$$</p><p> $$ i^2 = -1$$</p>
<p>Complex numbers are typically expressed as a linear combination of a real number and an imaginary number.</p>
<p>$$z = 3 + 2i$$</p><p>If you have any computational tasks that involve complex numbers, Python fortunately has a built-in module called "cmath" to be able to work with complex numbers.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cmath

<span class="hljs-comment"># Creating complex numbers</span>
complex_num1 = <span class="hljs-number">3</span> + <span class="hljs-number">4j</span>
complex_num2 = <span class="hljs-number">2</span> + <span class="hljs-number">3j</span>

<span class="hljs-comment">#arithmetic operations</span>
<span class="hljs-comment">#addition</span>
total = complex_num1 + complex_num2
<span class="hljs-comment">#print(total) --&gt; (5+7j)</span>

<span class="hljs-comment">#subtraction</span>
difference = complex_num1 - complex_num2
<span class="hljs-comment">#print(difference) --&gt; (1+1j)</span>

<span class="hljs-comment">#multiplication</span>
product = complex_num1 * complex_num2
<span class="hljs-comment">#print(product) --&gt; (-6+17j)</span>

<span class="hljs-comment">#division</span>
quotient = complex_num1 / complex_num2
<span class="hljs-comment">#print(quotient) --&gt; (1.3846153846153848-0.07692307692307697j)</span>

<span class="hljs-comment">#complex conjugate</span>
conjugate = complex_num1.conjugate()
<span class="hljs-comment">#print(conjugate) --&gt; (3-4j)</span>

<span class="hljs-comment">#magnitude</span>
magnitude = abs(complex_num1)
<span class="hljs-comment">#print(magnitude) --&gt; 5.0</span>
</code></pre>
<hr />
<h2 id="heading-iii-string-data-types">III. String data types</h2>
<p><img src="https://images.unsplash.com/photo-1581544291234-31340be4b1b8?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1548&amp;q=80" alt="a close up of a pile of colorful wooden blocks with letters on them" class="image--center mx-auto" /></p>
<p>String data types are another very basic type of data in Python. These data types are utilized to store and manipulate sequences of characters, such as letters, numbers, symbols, and whitespace. Strings play a crucial role in various programming tasks, including data manipulation, user input processing, and output formatting.</p>
<h3 id="heading-a-strings">a) Strings</h3>
<p>Strings are data objects that can store any of the characters on a keyboard.</p>
<p>When you declare and store a string in Python, you can use either single or double quotes to encapsulate the characters that are part of your string.</p>
<p>There are a large number of operations and functions that can be applied to strings in Python.</p>
<p>When working with strings there are some important things to know/remember:</p>
<ul>
<li>Capitalization matters. Each letter has a separate memory allocation for the uppercase and lowercase versions of the letter</li>
</ul>
<pre><code class="lang-python">x = <span class="hljs-string">'H'</span>
y = <span class="hljs-string">'h'</span>
are_they_equal = x == y
<span class="hljs-comment">#print(are_they_equal) --&gt; False</span>
</code></pre>
<ul>
<li><p>You can access an individual character in a string by referencing the character's index in the string</p>
</li>
<li><p>The index of the first letter in a string is 0.</p>
</li>
</ul>
<pre><code class="lang-python">x = <span class="hljs-string">'Cat'</span>
first_letter = x[<span class="hljs-number">0</span>]
<span class="hljs-comment">#print(first_letter) --&gt; 'C'</span>
</code></pre>
<p>Here are some of the most basic string operations and functions that you can use in Python.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating strings</span>
string1 = <span class="hljs-string">"Hello"</span> <span class="hljs-comment">#double quotes</span>
string2 = <span class="hljs-string">'World'</span> <span class="hljs-comment">#single quotes</span>

<span class="hljs-comment">#concatenation</span>
concatenated_string = string1 + string2
<span class="hljs-comment">#print(concatenated_string) --&gt; 'HelloWorld'</span>

<span class="hljs-comment">#length of a string</span>
length = len(string1)
<span class="hljs-comment">#print(length) --&gt; 5</span>

<span class="hljs-comment">#accessing characters in a string</span>
first_char = string1[<span class="hljs-number">0</span>]
<span class="hljs-comment">#print(first_char) --&gt; 'H'</span>

<span class="hljs-comment">#slicing a string</span>
substring = string1[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>] <span class="hljs-comment">#from 1st index up until 4th index of string</span>
<span class="hljs-comment">#print(substring) --&gt; 'ell'</span>

<span class="hljs-comment">#repeating a string</span>
repeated_string = string1 * <span class="hljs-number">3</span>
<span class="hljs-comment">#print(repeated_string) --&gt; 'HelloHelloHello'</span>

<span class="hljs-comment">#converting to uppercase</span>
uppercase_string = string1.upper()
<span class="hljs-comment">#print(uppercase_string) --&gt; 'HELLO'</span>

<span class="hljs-comment"># Converting to lowercase</span>
lowercase_string = string1.lower()
<span class="hljs-comment">#print(lowercase_string) --&gt; 'hello'</span>
</code></pre>
<hr />
<h2 id="heading-iv-ordered-sequence-data-types">IV. Ordered sequence data types</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695711373641/e98e6fcf-aad7-4dba-aa31-4d002e667578.png" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://iconscout.com/3ds/notes"><em>Free Notes 3D Illustration</em></a> <em>by</em> <a target="_blank" href="https://iconscout.com/contributors/iqonic-design"><em>iqonic.design</em></a> <em>on</em> <a target="_blank" href="https://iconscout.com"><em>IconScout</em></a><em>.</em></p>
<p>Sequence data types are objects that can be used to store sequences of numbers, strings, and other data types.</p>
<p>In sequence data types, each data object within the sequence is separated by a comma, and each sequence data type is declared using different symbols.</p>
<h3 id="heading-a-lists">a) Lists</h3>
<p>Lists are objects that can store and manipulate data. Since we can change/mutate the data inside of a list, we say that lists are <em>mutable</em> data types.</p>
<p>Some important things to know/remember about lists:</p>
<ul>
<li><p>Similar to strings, the index of the first element in a list is 0.</p>
</li>
<li><p>Lists are declared using square braces [].</p>
</li>
<li><p>Lists can store lists (these are called sublists).</p>
</li>
<li><p>You can iterate through lists either from the first index (starting at 0 and iterating by 1) or from the last index (starting at -1 and iterating by -1).</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a list</span>
my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, [<span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]]

<span class="hljs-comment">#accessing elements by ascending order</span>
first_element = my_list[<span class="hljs-number">0</span>]
<span class="hljs-comment">#print(first_element) --&gt; 1</span>

<span class="hljs-comment">#accessing elements by descending order</span>
last_element = my_list[<span class="hljs-number">-1</span>]
<span class="hljs-comment">#print(last_element) --&gt; [6, 7, 8]</span>

<span class="hljs-comment">#accessing elements within sublists</span>
last_element_in_sublist = my_list[<span class="hljs-number">-1</span>][<span class="hljs-number">2</span>]
<span class="hljs-comment">#print(last_element_in_sublist) --&gt; 8</span>

<span class="hljs-comment">#modifying elements by index</span>
my_list[<span class="hljs-number">1</span>] = <span class="hljs-number">7</span>
<span class="hljs-comment">#print(my_list) --&gt; [1, 7, 3, 4, 5, [6, 7, 8]]</span>

<span class="hljs-comment">#adding elements to end of list</span>
my_list.append(<span class="hljs-number">6</span>) 
<span class="hljs-comment">#print(my_list) --&gt; [1, 7, 3, 4, 5, [6, 7, 8], 6]</span>

<span class="hljs-comment">#adding elements to specific index of list</span>
my_list.insert(<span class="hljs-number">2</span>, <span class="hljs-number">8</span>) <span class="hljs-comment">#inserts the integer 8 at index 2</span>
<span class="hljs-comment">#print(my_list) --&gt; [1, 7, 8, 3, 4, 5, [6, 7, 8], 6]</span>

<span class="hljs-comment">#removing elements by value</span>
my_list.remove(<span class="hljs-number">8</span>) <span class="hljs-comment">#removes the integer 8</span>
<span class="hljs-comment">#print(my_list) --&gt; [1, 7, 3, 4, 5, [6, 7, 8], 6]</span>

<span class="hljs-comment">#removing elements by index</span>
<span class="hljs-keyword">del</span> my_list[<span class="hljs-number">0</span>] <span class="hljs-comment">#removes element at index 0</span>
<span class="hljs-comment">#print(my_list) --&gt; [7, 3, 4, 5, [6, 7, 8], 6]</span>

<span class="hljs-comment">#removing last element in a list</span>
<span class="hljs-comment">#this method also returns the last element</span>
last_element_removed = my_list.pop()
<span class="hljs-comment">#print(last_element_removed) --&gt; 6</span>
<span class="hljs-comment">#print(my_list) --&gt; [7, 3, 4, 5, [6, 7, 8]]</span>

<span class="hljs-comment">#slicing a list</span>
sub_list = my_list[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]
<span class="hljs-comment">#print(sub_list) --&gt; [3, 4, 5]</span>

<span class="hljs-comment">#list length</span>
list_length = len(my_list)
<span class="hljs-comment">#print(list_length) --&gt; 5</span>

<span class="hljs-comment">#arrange list from least to greatest</span>
<span class="hljs-comment">#since there's a sublist stored in our list, this will return an error</span>
<span class="hljs-comment">#so let's first remove the sublist</span>
my_list.pop()
my_list.sort()
<span class="hljs-comment">#print(my_list) --&gt; [3, 4, 5, 7]</span>

<span class="hljs-comment">#arrange list from greatest to least</span>
my_list.sort(reverse=<span class="hljs-literal">True</span>)
<span class="hljs-comment">#print(my_list) --&gt; [7, 5, 4, 3]</span>

<span class="hljs-comment">#reverse order of elements</span>
my_list.reverse()
<span class="hljs-comment">#print(my_list) --&gt; [3, 4, 5, 7]</span>

<span class="hljs-comment">#return number of occurences of element in list</span>
count_of_7 = my_list.count(<span class="hljs-number">7</span>)
<span class="hljs-comment">#print(count_of_7) --&gt; 1</span>

<span class="hljs-comment">#return index of FIRST occurence of element</span>
index_of_7 = my_list.index(<span class="hljs-number">7</span>)
<span class="hljs-comment">#print(index_of_7) --&gt; 3</span>

<span class="hljs-comment">#delete all the elements inside a list</span>
my_list.clear()
<span class="hljs-comment">#print(my_list) --&gt; []</span>

<span class="hljs-comment">#concatenating two lists</span>
list1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list2 = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
concatenated_list = list1 + list2
<span class="hljs-comment">#print(concatenated_list) --&gt; [1, 2, 3, 4, 5, 6]</span>

<span class="hljs-comment">#repeating a list</span>
repeated_list = list1 * <span class="hljs-number">3</span>
<span class="hljs-comment">#print(repeated_list) --&gt; [1, 2, 3, 1, 2, 3, 1, 2, 3]</span>
</code></pre>
<h3 id="heading-b-tuples">b) Tuples</h3>
<p>The biggest difference between tuples and lists is that tuples are <em>immutable</em>.</p>
<p>This means that after a tuple is made, there's not anything we can do to modify/mutate the data inside a tuple like we can with lists.</p>
<p>While this might seem like a large disadvantage at first, tuples serve a unique purpose of storing data that is not meant to ever change.</p>
<p>For example, if you wanted to store the RGB value for pure red, you should use a tuple since the RGB value for pure red is a value that remains constant.</p>
<p>Other than the fact that tuples are immutable and are declared using parentheses instead of square braces, tuples and lists are pretty similar.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a tuple</span>
my_tuple = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)

<span class="hljs-comment">#accessing elements in a tuple</span>
first_element = my_tuple[<span class="hljs-number">0</span>]
<span class="hljs-comment">#print(first_element) --&gt; 1</span>

<span class="hljs-comment">#tuple slicing</span>
sub_tuple = my_tuple[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]
<span class="hljs-comment">#print(sub_tuple) --&gt; (2, 3, 4)</span>

<span class="hljs-comment">#length of a tuple</span>
length = len(my_tuple)
<span class="hljs-comment">#print(length) --&gt; 5</span>

<span class="hljs-comment">#counting occurrences of an element in a tuple</span>
count_of_3 = my_tuple.count(<span class="hljs-number">3</span>)
<span class="hljs-comment">#print(count_of_3) --&gt; 1</span>

<span class="hljs-comment">#return index of FIRST occurence of element</span>
index_of_4 = my_tuple.index(<span class="hljs-number">4</span>)
<span class="hljs-comment">#print(index_of_4) --&gt; 3</span>

<span class="hljs-comment">#concatenating two tuples</span>
tuple1 = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
tuple2 = (<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>)
concatenated_tuple = tuple1 + tuple2
<span class="hljs-comment">#print(concatenated_tuple) --&gt; (1, 2, 3, 4, 5, 6)</span>

<span class="hljs-comment">#repeating a tuple</span>
repeated_tuple = tuple1 * <span class="hljs-number">3</span>
<span class="hljs-comment">#print(repeated_tuple) --&gt; (1, 2, 3, 1, 2, 3, 1, 2, 3)</span>
</code></pre>
<hr />
<h2 id="heading-v-unordered-sequence-data-types">V. Unordered sequence data types</h2>
<p>Unordered sequences are sequences of data objects that have no specified index.</p>
<p>The key reason for this is that unordered sequence data types don't allocate any memory to the order in which elements are added to the sequence. This makes unordered sequence data types much faster to work with in terms of computing power.</p>
<h3 id="heading-a-sets">a) Sets</h3>
<p>Similar to lists, sets are mutable, so you can modify/mutate the elements inside sets.</p>
<p>Although, unlike both lists and tuples, sets don't have repeat values.</p>
<p>While you won't get an error for trying to declare a set with repeat values, Python will simply ignore the repeat values you entered when storing the set in memory.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating sets</span>
set1 = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}
set2 = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>}

<span class="hljs-comment">#adding unique element to a set</span>
set1.add(<span class="hljs-number">5</span>)
<span class="hljs-comment">#print(set1) --&gt; {1, 2, 3, 4, 5}</span>

<span class="hljs-comment">#adding repeat element to a set</span>
set1.add(<span class="hljs-number">2</span>)
<span class="hljs-comment">#print(set1) --&gt; {1, 2, 3, 4, 5}</span>

<span class="hljs-comment">#removing an element from a set</span>
set1.remove(<span class="hljs-number">1</span>)
<span class="hljs-comment">#print(set1) --&gt; {2, 3, 4, 5}</span>

<span class="hljs-comment">#union of sets</span>
<span class="hljs-comment">#union is all the elements from two sets (without repeating elements)</span>
union_set = set1.union(set2)
<span class="hljs-comment">#print(union_set) --&gt; {2, 3, 4, 5, 6}</span>

<span class="hljs-comment">#intersection of sets</span>
<span class="hljs-comment">#intersection is all the shared elements from two sets</span>
intersection_set = set1.intersection(set2)
<span class="hljs-comment">#print(intersection_set) --&gt; {3, 4, 5}</span>

<span class="hljs-comment">#difference of sets</span>
<span class="hljs-comment">#difference is all the elements in the first set but not in the second set</span>
difference_set = set1.difference(set2)
<span class="hljs-comment">#print(difference_set) --&gt; {2}</span>

<span class="hljs-comment">#checking if a set is a subset of another set</span>
<span class="hljs-comment">#set is a subset of another set if ALL of its elements are contained in the other set</span>
<span class="hljs-comment">#for example, the set of integers is a subset of the set of rational numers</span>
is_subset = set1.issubset(set2)
<span class="hljs-comment">#print(is_subset) --&gt; False</span>

<span class="hljs-comment">#checking if a set is a superset of another set</span>
<span class="hljs-comment">#set is a superset of another set if ALL of the elements from the other set are contained in the first set</span>
<span class="hljs-comment">#for example, the set of real numbers is a superset of the set of the irrational numbers</span>
is_superset = set1.issuperset(set2)
<span class="hljs-comment">#print(is_superset) --&gt; False</span>

<span class="hljs-comment">#checking if two sets are disjoint (no common elements)</span>
are_disjoint = set1.isdisjoint(set2)
<span class="hljs-comment">#print(are_disjoint) --&gt; False</span>
</code></pre>
<hr />
<h2 id="heading-vi-mapping-data-types">VI. Mapping data types</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695712112041/19cc539c-2944-48b5-86db-1af22116c9da.png" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://iconscout.com/3ds/key-folder"><em>Free Key Folder 3d Icon</em></a> <em>by</em> <a target="_blank" href="https://iconscout.com/contributors/rizkiahmadfauzi28"><em>Rizki Ahmad Fauzi</em></a></p>
<p>The last basic data type to go over in Python is the mapping data type.</p>
<p>Mapping data types map/connect one data object with another data object stored as a pair of data.</p>
<p>Similar to sequences of data, mapping data types can store comma-separated collections of data. However, unlike the sequence data types, the collection of data in mapping data types is pairs of data objects.</p>
<h3 id="heading-a-dictionaries">a) Dictionaries</h3>
<p>Similar to lists and tuples, dictionaries are ordered collections of data. However, this is only the case as of Python 3.7. For Python 3.6 and earlier, dictionaries are unordered.</p>
<p>Also, similar to lists and sets, dictionaries are mutable.</p>
<p>Finally, similar to sets, the first data object (simply referred to as <em>keys</em>) of a pair in a dictionary can't be repeated. However, the second data object (simply referred to as <em>values</em>) of a pair in a dictionary <strong>can</strong> be repeated.</p>
<p>Dictionary keys can either be numbers or strings, and dictionary values can be of any data type (dictionary values can even be dictionaries).</p>
<p>The most practical way to look at dictionaries is to see them as data objects for storing attributes of one or more things.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a dictionary</span>
my_dog = {<span class="hljs-string">'breed'</span>: <span class="hljs-string">'husky'</span>, <span class="hljs-string">'color'</span>: <span class="hljs-string">'grey'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">2</span>}

<span class="hljs-comment">#accessing a value using a key</span>
breed = my_dog[<span class="hljs-string">'breed'</span>]
<span class="hljs-comment">#print(breed) --&gt; 'husky'</span>

<span class="hljs-comment">#adding a new key-value pair</span>
my_dog[<span class="hljs-string">'name'</span>] = <span class="hljs-string">'max'</span>
<span class="hljs-comment">#print(my_dog) --&gt; {'breed': 'husky', 'color': 'grey', 'age': 2, 'name': 'max'}</span>

<span class="hljs-comment">#updating a value</span>
my_dog[<span class="hljs-string">'age'</span>] = <span class="hljs-number">3</span>
<span class="hljs-comment">#print(my_dog) --&gt; {'breed': 'husky', 'color': 'grey', 'age': 3, 'name': 'max'}</span>

<span class="hljs-comment">#removing a key-value pair</span>
<span class="hljs-keyword">del</span> my_dog[<span class="hljs-string">'color'</span>]
<span class="hljs-comment">#print(my_dog) --&gt; {'breed': 'husky', 'age': 3, 'name': 'max'}</span>

<span class="hljs-comment">#checking if a key is in the dictionary</span>
name_exists = <span class="hljs-string">'name'</span> <span class="hljs-keyword">in</span> my_dog
<span class="hljs-comment">#print(name_exists) --&gt; True</span>

<span class="hljs-comment">#getting all keys</span>
keys = my_dog.keys()
<span class="hljs-comment">#print(keys) --&gt; dict_keys(['breed', 'age', 'name'])</span>

<span class="hljs-comment">#getting all values</span>
values = my_dog.values()
<span class="hljs-comment">#print(values) --&gt; dict_values(['husky', 3, 'max'])</span>
</code></pre>
<hr />
<h2 id="heading-vii-conclusion">VII. Conclusion</h2>
<p>I hope that after reading this article, you now feel comfortable with some of the basic operations and functions that can be applied to many of the built-in data types in Python.</p>
<p>You have learned the basics of booleans, integers, floats, complex numbers, strings, lists, tuples, sets, and dictionaries in Python, and got exposed to the syntactical rules and logic governing these data types in Python.</p>
<p>If you have any lingering questions that you'd like me to answer, please ask away in the comments below.</p>
<p>Additionally, if you have any suggestions for an article topic you'd like me to cover in the future, feel free to drop those in the comments below as well.</p>
<p>Finally, make sure to follow my newsletter so that you never miss out on when I post new content!</p>
]]></content:encoded></item><item><title><![CDATA[Training Neural Networks: A Starter's Guide to Gradient Descent]]></title><description><![CDATA[In this article, we explore the concept of optimization in machine learning models and the math behind gradient descent. We discuss the components of gradient descent, including cost functions, partial derivatives, gradients, and learning rates. By u...]]></description><link>https://scrappedscript.com/training-neural-networks-a-starters-guide-to-gradient-descent</link><guid isPermaLink="true">https://scrappedscript.com/training-neural-networks-a-starters-guide-to-gradient-descent</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Thu, 28 Sep 2023 21:31:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695251986785/c801fb9a-0d47-4012-b5bc-7275134b2236.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>In this article, we explore the concept of optimization in machine learning models and the math behind gradient descent. We discuss the components of gradient descent, including cost functions, partial derivatives, gradients, and learning rates. By understanding these concepts, we can improve the accuracy of machine learning models.</p>
</blockquote>
<h1 id="heading-introduction">Introduction</h1>
<p><img src="https://images.unsplash.com/photo-1596496181871-9681eacf9764?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1486&amp;q=80" alt="a woman writing on a whiteboard with a marker" class="image--center mx-auto" /></p>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/log-base-two"><strong>Log Base Two</strong></a><strong>", a series dedicated to the relationship between math and computer science</strong>.</p>
<p>Just to give a bit of background on my experience in math, I've <strong>excelled</strong> in a total of 10 college courses in math:</p>
<ol>
<li><p><strong>Single-variable differential calculus</strong></p>
</li>
<li><p><strong>Single-variable integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus</strong></p>
</li>
<li><p><strong>Multi-variable differential and integral calculus of vector-valued functions</strong></p>
</li>
<li><p><strong>Linear Algebra</strong></p>
</li>
<li><p><strong>Differential equations</strong></p>
</li>
<li><p><strong>Probability and statistics</strong></p>
</li>
<li><p><strong>Data analysis using R programming language</strong></p>
</li>
<li><p><strong>Multivariate statistics</strong></p>
</li>
<li><p><strong>Discrete math</strong></p>
</li>
</ol>
<p>For a large majority of those 10 classes, I ended up with A's.</p>
<p>Although, before college, I struggled a lot with math in the classroom, even though math had always been my favorite subject since I was in elementary school. I found it hard to truly grasp the concepts taught because my high school teachers were too focused on skill assessment. Instead of focusing on the actual concept being taught, I was too worried about how I was going to pass the test the following week.</p>
<p>Once I got to college, I realized that your math grade (or any grade for that matter) truly doesn't define your potential. Further, I'd argue that your success in math <em>education</em> is heavily influenced by the quality of the teacher/professor's teaching.</p>
<p>My mission with this series is to show other people that math isn't so scary if you break down mathematical concepts into digestible bouts of information and investigate use cases of math in your primary field of interest (in this case, computer science). Along the way, I hope to also supplement your math education with quality content. I believe that <strong>everyone</strong> is capable of learning and truly loving mathematics.</p>
<p><strong>New articles in this series are posted every Thursday!</strong></p>
<hr />
<h1 id="heading-optimization">Optimization</h1>
<p>Imagine for a moment that you're in the process of trying to teach basic shapes to your child.</p>
<p>You might start by using a variety of strategies to have your child exposed to different shapes.</p>
<p>For example, you might use art activities, playtime, children's books, and children's TV shows to start.</p>
<p>Although, you start to notice that your child is most interested in shapes during playtime.</p>
<p>As a result, to optimize their shape learning, you start focusing more on playtime activities and techniques, and less on other strategies.</p>
<p>In machine learning models, computer scientists use this same concept to train neural networks and increase the accuracy of a machine learning model's output.</p>
<h2 id="heading-optimization-in-machine-learning">Optimization in machine learning</h2>
<p><img src="https://images.unsplash.com/photo-1677442135703-1787eea5ce01?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1632&amp;q=80" alt="a computer circuit board in the shape of a brain" class="image--center mx-auto" /></p>
<p>In machine learning models, the main goal is to increase the output accuracy of the model's results.</p>
<p>Each time we run data through a model, we go back and make adjustments to the neural network to optimize how the model learns.</p>
<p>One of the ways to optimize neural networks is with a technique called gradient descent.</p>
<h2 id="heading-overview-of-gradient-descent">Overview of gradient descent</h2>
<p>Gradient descent is a technique from multi-variable calculus.</p>
<p>The main idea of gradient descent is to take some function with multiple independent variables and find where that function has its lowest output value. In calculus, this lowest value is called a local minimum.</p>
<p>The process of gradient descent starts with taking some random input, and then moving some distance in the direction of the negative gradient. We keep iterating this step until we reach the local minimum of the function.</p>
<p>It's as if someone plops you in the middle of a hilly terrain with a blindfold on and your goal is to go towards the lowest nearby point in the hilly terrain. You can accomplish this by iteratively taking steps toward the direction where it feels like you're moving downhill. Eventually, after enough steps, you'll reach the local minimum.</p>
<hr />
<h1 id="heading-components-of-gradient-descent">Components of gradient descent</h1>
<p>The gradient descent algorithm has 5 main components to understand:</p>
<ul>
<li><strong>The current value of the parameter</strong></li>
</ul>
<p>$$\theta_j$$</p><ul>
<li><strong>The cost function</strong></li>
</ul>
<p>$$J(\theta)$$</p><ul>
<li><strong>The size of each step (this is called the learning rate in machine learning)</strong></li>
</ul>
<p>$$\alpha$$</p><ul>
<li><strong>The direction of steepest descent (the partial derivative of the cost function with respect to the parameter)</strong></li>
</ul>
<p>$$\frac{\partial J(\theta)}{\partial \theta}$$</p><ul>
<li><strong>The next value of the parameter</strong></li>
</ul>
<p>$$\theta_{j+1}$$</p><p>Putting it all together in a mathematical equation:</p>
<p>$$\theta_{j+1} = \theta_j - \alpha \frac{\partial J(\theta)}{\partial \theta}$$</p><h2 id="heading-cost-function">Cost function</h2>
<p>A cost function is a function that calculates the "cost" of one or more variables/parameters.</p>
<p>The cost of a function is an intuitive function to calculate the difference between predicted values and actual values.</p>
<p>The cost function you use in a model depends on the type of problem you're trying to solve.</p>
<p>If you're trying to make a prediction, then you'll use a regression cost function. Alternatively, if you're trying to classify data, you'll use a binary or multi-class classification cost function.</p>
<p>An example of a regression cost function is the mean absolute error:</p>
<p>$$\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|$$</p><p>The mean absolute error calculates the sum of the differences between predicted values and actual values and is then divided by the amount of data points in the dataset to find the average error value.</p>
<p>As stated before, the cost function you use in your gradient descent algorithm will vary based on the problem you're trying to solve and the nature of your dataset.</p>
<h2 id="heading-gradients-and-partial-derivatives">Gradients and partial derivatives</h2>
<h3 id="heading-derivatives">Derivatives</h3>
<p>If you've taken single-variable calculus, you're probably familiar with derivatives of single-variable functions.</p>
<p>$$\frac{d}{dx}f(x)$$</p><p>If not, then just understand that the main idea of a derivative is to find the rate at which a variable is changing with respect to another variable.</p>
<p>For example, the speed of a car is the rate, or derivative, at which the car is moving with respect to time (e.g. miles <em>per</em> hour).</p>
<h3 id="heading-partial-derivatives">Partial derivatives</h3>
<p>In functions with multiple independent variables, we take the partial derivative of the dependent variable with respect to an independent variable, while holding the other independent variables constant.</p>
<p>$$\frac{\partial}{\partial x}f(x,y)$$</p><p>For example, to find the rate at which the height of water in a glass changes, we'd take the partial derivative of the height of the glass with respect to the volume of the glass.</p>
<h3 id="heading-gradients">Gradients</h3>
<p><img src="https://images.unsplash.com/photo-1604357209793-fca5dca89f97?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1528&amp;q=80" alt="a person holding a cell phone with a map on it" class="image--center mx-auto" /></p>
<p>To encapsulate all of the partial derivatives of a function, we take the gradient of a function.</p>
<p>$$\nabla f(x, y) = \pmatrix {\frac{\partial}{\partial x} f(x,y) \\ \frac{\partial}{\partial y} f(x,y) }$$</p><p>The gradient of a function is a vector field that represents the direction of the greatest change of a function. Each element in the gradient vector is a single partial derivative with respect to some independent variable.</p>
<p>If you're not sure what vectors are, then make sure to go read my article from last week: The Matrix Is Everywhere: Linear Algebra Concepts Relevant to Computer Science.</p>
<p>For example, to find the direction to walk to reach the top of a hill, we'd take the gradient of the height of the hill. The first element in this gradient would tell me how far to go north or south, and the second element would tell me how far to go east or west.</p>
<p>In gradient descent, we take the gradient of the cost function to find the direction of the greatest error in our predictions (and then intuitively go in the negative direction so we reach the point at which the error in our predictions is minimized).</p>
<h2 id="heading-learning-rate">Learning rate</h2>
<p>The last gradient descent component to analyze is the learning rate.</p>
<p>In supervised machine learning models, you assign the learning rate of the model.</p>
<p>The learning rate ultimately controls how far the model goes in the direction of steepest descent (the negative of the gradient of the cost function).</p>
<p>It should be noted that the learning rate is not constant, and there are many different algorithms used to optimize the learning rate.</p>
<p>Similar to the cost function, the learning rate you use is dependent on the problem you're trying to solve.</p>
<p>If the learning rate is too small, then the training of the model will take too long.</p>
<p>Alternatively, if the learning rate is too large, then the model may "overshoot" the local minimum.</p>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this article, we went over the very basics of the math used in gradient descent. You learned about the concept of optimization in machine learning models, the intuition behind gradient descent, and all of the components of gradient descent broken down.</p>
<p>If you have any lingering questions or suggestions for a topic you want me to cover in the future, then please make sure to leave a comment down below.</p>
<p>Lastly, make sure to follow my newsletter to never miss out on when I post new content!</p>
]]></content:encoded></item><item><title><![CDATA[Which Programming Language Should You Learn First?]]></title><description><![CDATA[In this article, I discuss the importance of choosing your first programming language and factors to consider when making your selection. I also provide recommendations for the best programming languages to learn first for various fields, such as web...]]></description><link>https://scrappedscript.com/which-programming-language-should-you-learn-first</link><guid isPermaLink="true">https://scrappedscript.com/which-programming-language-should-you-learn-first</guid><category><![CDATA[Python]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Tue, 26 Sep 2023 17:58:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ZIPFteu-R8k/upload/b3acb501bdac5b8ae9b59ab89554236f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>In this article, I discuss the importance of choosing your first programming language and factors to consider when making your selection. I also provide recommendations for the best programming languages to learn first for various fields, such as web development, mobile app development, machine learning, and cybersecurity. Ultimately, the first language you learn should align with your personal interests, goals, and desired career path, but remember that the core of software development is problem-solving using logic, which can be applied to any programming language.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/bit-by-bit"><strong>Bit by Bit</strong></a><strong>", a series devoted to all things programming. Whether you're still a computer science undergrad or the CTO of Apple, there's something for you here.</strong></p>
<p><strong>New articles in this series are posted every Tuesday!</strong></p>
<hr />
<h1 id="heading-importance-of-choosing-your-first-programming-language">Importance of choosing your first programming language</h1>
<p>If you've chosen to enroll in a university, then the first programming language you learn is dependent upon the language that's used in your university's Intro to Programming course.</p>
<p>But if you've made the courageous decision to take the self-taught route of learning software development, then you have to make that nerve-wracking decision of which programming language you'll learn first.</p>
<p>But I'd argue that the first programming language you learn doesn't mean anything in the grand scheme of things.</p>
<p>What's most important in learning software development is not which languages you can code in or how you can memorize a language's syntax.</p>
<p>No matter which type of development you decide to do, the core of all software development is the ability to solve problems using logic.</p>
<p>Based on my own journey, I know firsthand that the first language that one learns means almost nothing.</p>
<p>The first programming language I learned was RobotC in a class I took on cognitive robotics, a required course for my B.A. in psychology.</p>
<p>RobotC is a high-level programming language based on the C programming language and is almost exclusively used for robotics programming in educational settings.</p>
<p>So basically, it's a language that I'll probably never use again.</p>
<p>However, this course taught me how to <em>think</em> like a software engineer and stimulated my interest in computer science.</p>
<p>Moral of the story? All that matters in learning your first language is that you learn the core of what software engineering is all about.</p>
<hr />
<h1 id="heading-factors-to-consider-when-selecting-a-programming-language">Factors to consider when selecting a programming language</h1>
<p>I know I just said that the programming language you learn first doesn't matter, but there's also no issue with wanting to start with learning a language geared toward the overall path that you want to take.</p>
<p>With that being said, here are some factors that you could consider when choosing your first programming language.</p>
<h2 id="heading-personal-interests">Personal interests</h2>
<p>The most important factor in choosing your first programming language is considering who you are as an individual.</p>
<p>Forget about all the external pressure of choosing the most in-demand language.</p>
<p>What matters is choosing something for yourself so you stay motivated to continue growing in software engineering.</p>
<h2 id="heading-personal-goals">Personal goals</h2>
<p>The second factor you should consider is what you ultimately want to create with software engineering.</p>
<p>While some programming languages can be used in pretty much every type of development, some languages can only be used in <strong>one</strong> type of development (such as my first language, RobotC).</p>
<p>For this reason, if you want to increase the chances of learning a language that you'll use for the rest of your journey, then it's important to think about what exactly you want to build.</p>
<h2 id="heading-community-support">Community support</h2>
<p>You are far more likely to stay motivated if you learn with others than if you learn alone.</p>
<p>Additionally, choosing a language that is "popular" will increase the likelihood that you can find an opportunity to collaborate on a project with a team, or contribute to an open-source project.</p>
<h2 id="heading-ease-of-learning">Ease of learning</h2>
<p>Some people may tell you to first learn a language like Java or C++ so that you understand how computers compile code into machine instructions.</p>
<p>However, <em>compiled</em> languages can be very difficult to learn as a first language.</p>
<p>Software engineering takes a lot of grit as it is, so it's best to start with an <em>interpreted</em> language to get the fundamentals down.</p>
<h2 id="heading-versatility">Versatility</h2>
<p>If you don't have a set goal in mind with software engineering, then this point is especially important.</p>
<p>Choosing a versatile language will allow you to maximize the variety of types of projects that you can create while learning your first language, as well as enable you to test different types of development to see what you like best.</p>
<h2 id="heading-job-market-and-industry-trends">Job market and industry trends</h2>
<p><img src="https://images.unsplash.com/photo-1521790797524-b2497295b8a0?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1469&amp;q=80" alt="a close up of two people shaking hands" class="image--center mx-auto" /></p>
<p>I'd argue that this factor should hold the least weight in choosing your first language to learn.</p>
<p>There are always trendy languages and libraries coming and going. While these trendy languages have a strong moment, a lot of them eventually fade away.</p>
<p>You should start with learning one of the core languages that have stood strong for decades, as these languages are probably not going anywhere anytime soon.</p>
<p>Additionally, the job market's demand for developers with a background in a specific language is always changing.</p>
<hr />
<h1 id="heading-best-programming-language-to-learn-first-overall">Best programming language to learn first overall</h1>
<h2 id="heading-python">Python</h2>
<h3 id="heading-uses">Uses</h3>
<ul>
<li><p>Web development</p>
</li>
<li><p>Scientific computing</p>
</li>
<li><p>Machine learning and artificial intelligence</p>
</li>
<li><p>Desktop app development</p>
</li>
<li><p>Data analysis</p>
</li>
<li><p>Data visualization</p>
</li>
<li><p>API development</p>
</li>
<li><p>Language development</p>
</li>
<li><p>Blockchain development</p>
</li>
<li><p>Quality assurance software testing</p>
</li>
</ul>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Easy to learn and use</p>
</li>
<li><p>Incredibly versatile</p>
</li>
<li><p>Strong community of developers</p>
</li>
<li><p>Free and open-source</p>
</li>
<li><p>Cross-platform</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Slow speed</p>
</li>
<li><p>Heavy memory usage</p>
</li>
</ul>
<hr />
<h1 id="heading-best-programming-language-to-learn-first-for-web-development">Best programming language to learn first for web development</h1>
<p><img src="https://images.unsplash.com/photo-1669023414162-8b0573b9c6b2?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1632&amp;q=80" alt="a computer monitor sitting on top of a desk next to a keyboard" class="image--center mx-auto" /></p>
<h2 id="heading-javascript">JavaScript</h2>
<h3 id="heading-uses-within-web-development">Uses within web development</h3>
<ul>
<li><p>Dynamic webpage development</p>
</li>
<li><p>Browser-side scripting</p>
</li>
<li><p>Server-side scripting</p>
</li>
<li><p>Web API development</p>
</li>
</ul>
<h3 id="heading-pros-1">Pros</h3>
<ul>
<li><p>Large selection of built-in and external libraries</p>
</li>
<li><p><em>Practically</em> the only programming language that is used for browser-side scripting</p>
</li>
<li><p>Easy to learn and use</p>
</li>
<li><p>Strong community of developers</p>
</li>
<li><p>Free to use</p>
</li>
</ul>
<h3 id="heading-cons-1">Cons</h3>
<ul>
<li><p>Requires a run-time environment</p>
</li>
<li><p>Beginner mistakes can easily lead to security risks and vulnerabilities</p>
</li>
<li><p>Not very versatile outside of web development</p>
</li>
</ul>
<hr />
<h1 id="heading-best-programming-language-to-learn-first-for-mobile-app-development">Best programming language to learn first for mobile app development</h1>
<p><img src="https://images.unsplash.com/photo-1546054454-aa26e2b734c7?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1480&amp;q=80" alt="two iphones sitting next to each other on a white surface" class="image--center mx-auto" /></p>
<h2 id="heading-swift">Swift</h2>
<h3 id="heading-uses-within-mobile-app-development">Uses within mobile app development</h3>
<ul>
<li><p>iOS app development</p>
</li>
<li><p>Android app development</p>
</li>
</ul>
<h3 id="heading-pros-2">Pros</h3>
<ul>
<li><p>Besides Objective-C, Swift is the only programming language supported by iOS</p>
</li>
<li><p>Easy to learn and use</p>
</li>
<li><p>Free and open-source</p>
</li>
<li><p>Ability to develop both iOS and Android apps with a single code base</p>
</li>
<li><p>Incredibly fast</p>
</li>
</ul>
<h3 id="heading-cons-2">Cons</h3>
<ul>
<li><p>Not very versatile outside of mobile app development</p>
</li>
<li><p>Very new language</p>
</li>
<li><p>Small selection of external libraries</p>
</li>
<li><p>Small community of developers</p>
</li>
</ul>
<hr />
<h1 id="heading-best-programming-language-to-learn-first-for-machine-learning-and-artificial-intelligence">Best programming language to learn first for machine learning and artificial intelligence</h1>
<p><img src="https://images.unsplash.com/photo-1534723328310-e82dad3ee43f?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1472&amp;q=80" alt="a robot is holding a tablet with a picture on it" class="image--center mx-auto" /></p>
<h2 id="heading-python-1">Python</h2>
<h3 id="heading-uses-within-ml-and-ai">Uses within ML and AI</h3>
<ul>
<li><p>Unsupervised and supervised learning algorithms</p>
</li>
<li><p>Natural language processing</p>
</li>
<li><p>Facial recognition</p>
</li>
<li><p>Fraud detection</p>
</li>
<li><p>Refining search results</p>
</li>
<li><p>Spam detection</p>
</li>
<li><p>Pharmaceutical drug research analysis</p>
</li>
<li><p>Self-driving cars</p>
</li>
<li><p>Cancer research analysis</p>
</li>
<li><p>Financial analysis</p>
</li>
<li><p>Malware detection</p>
</li>
<li><p>Optimized digital marketing</p>
</li>
</ul>
<h3 id="heading-pros-of-using-python-for-ml-and-ai">Pros of using Python for ML and AI</h3>
<ul>
<li><p>Large selection and variety of external libraries meant for ML and AI</p>
</li>
<li><p>Large community of developers that use Python for ML and AI</p>
</li>
<li><p>Simple to use compared to other languages used for ML and AI</p>
</li>
<li><p>Incredibly versatile within the broad realm of "big data"</p>
</li>
<li><p>Easy to integrate due to Python's cross-platform nature</p>
</li>
</ul>
<h3 id="heading-cons-of-using-python-for-ml-and-ai">Cons of using Python for ML and AI</h3>
<ul>
<li>Slow speed</li>
</ul>
<hr />
<h1 id="heading-best-programming-language-to-learn-first-for-cybersecurity">Best programming language to learn first for cybersecurity</h1>
<p><img src="https://images.unsplash.com/photo-1660644808226-a5b2e691fc51?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1632&amp;q=80" alt="a hacker sitting at a table coding on computer" class="image--center mx-auto" /></p>
<h2 id="heading-python-2">Python</h2>
<h3 id="heading-uses-within-cybersecurity">Uses within cybersecurity</h3>
<ul>
<li><p>Network scanning</p>
</li>
<li><p>Vulnerability detection</p>
</li>
<li><p>Log analysis</p>
</li>
<li><p>Penetration testing</p>
</li>
<li><p>Malware analysis</p>
</li>
<li><p>Port scanning</p>
</li>
<li><p>Ethical hacking</p>
</li>
</ul>
<h3 id="heading-pros-3">Pros</h3>
<ul>
<li><p>Large selection and variety of external libraries meant for cybersecurity</p>
</li>
<li><p>Large community of developers that use Python for cybersecurity</p>
</li>
<li><p>Simple to use compared to other languages used for cybersecurity</p>
</li>
<li><p>Incredibly versatile within the broad realm of IoT</p>
</li>
<li><p>Easy to identify attacks from any operating system due to Python's cross-platform nature</p>
</li>
</ul>
<h3 id="heading-cons-3">Cons</h3>
<ul>
<li>Slow speed</li>
</ul>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope that after reading this article, you feel more confident in choosing your first programming language.</p>
<p>Remember that it's okay if you don't know what you want to do yet. As long as you focus on learning how to solve problems using logic, then you'll be able to translate that knowledge into any other language down the line.</p>
<p>At the same time, it's okay to want to start by learning a language that can directly be used in the type of development that you want to do in the future.</p>
<p>If you're about to start learning how to program and have chosen which language you want to learn, then please share which language you chose and why in the comments below!</p>
<p>If you have any lingering questions or suggestions for a topic you want me to cover in the future, feel free to post those in the comments as well.</p>
<p>Lastly, make sure to follow my newsletter so that you don't miss out on when I post new content.</p>
]]></content:encoded></item><item><title><![CDATA[The Matrix Is Everywhere: Linear Algebra Concepts Relevant to Computer Science]]></title><description><![CDATA[Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.

In this article, the author explores the relationship between mathematics and computer science, foc...]]></description><link>https://scrappedscript.com/the-matrix-is-everywhere-linear-algebra-concepts-relevant-to-computer-science</link><guid isPermaLink="true">https://scrappedscript.com/the-matrix-is-everywhere-linear-algebra-concepts-relevant-to-computer-science</guid><category><![CDATA[Mathematics]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Sirus Salari]]></dc:creator><pubDate>Thu, 21 Sep 2023 19:40:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/a17458d20a3a815e5372c9f31a2d811e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Disclosure: When you purchase through links on my site, I may earn an affiliate commission. As an Amazon Associate, I earn from qualifying purchases.</p>
<blockquote>
<p>In this article, the author explores the relationship between mathematics and computer science, focusing on the core concepts of linear algebra and their various applications in computer science. Topics covered include linear systems, matrices, Gaussian elimination, vectors, vector spaces, vector-matrix multiplication, and transformations. These concepts are essential in fields such as machine learning, computer graphics, cryptography, and information theory.</p>
</blockquote>
<hr />
<h1 id="heading-introduction">Introduction</h1>
<p><strong>This article is part of a series called "</strong><a target="_blank" href="https://scrappedscript.com/series/log-base-two"><strong>Log Base Two</strong></a><strong>", a series dedicated to the relationship between math and computer science</strong>.</p>
<p>Just to give a bit of background on my experience in math, I've <strong>excelled</strong> in a total of 10 college courses in math:</p>
<ol>
<li><p>Single-variable differential calculus</p>
</li>
<li><p>Single-variable integral calculus</p>
</li>
<li><p>Multi-variable differential and integral calculus</p>
</li>
<li><p>Multi-variable differential and integral calculus of vector-valued functions</p>
</li>
<li><p>Linear Algebra</p>
</li>
<li><p>Differential equations</p>
</li>
<li><p>Probability and statistics</p>
</li>
<li><p>Data analysis using R programming language</p>
</li>
<li><p>Multivariate statistics</p>
</li>
<li><p>Discrete math</p>
</li>
</ol>
<p>For a large majority of those 10 classes, I ended up with A's.</p>
<p>Although, before college, I struggled a lot with math in the classroom, even though math had always been my favorite subject since I was in elementary school. I found it hard to truly grasp the concepts taught because my high school teachers were too focused on skill assessment. Instead of focusing on the actual concept being taught, I was too worried about how I was going to pass the test the following week.</p>
<p>Once I got to college, I realized that your math grade (or any grade for that matter) truly doesn't define your potential. Further, I'd argue that your success in math <em>education</em> is heavily influenced by the quality of the teacher/professor's teaching.</p>
<p>My mission with this series is to show other people that math isn't so scary if you break down mathematical concepts into digestible bouts of information and investigate use cases of math in your primary field of interest (in this case, computer science). Along the way, I hope to also supplement your math education with quality content. I believe that <strong>everyone</strong> is capable of learning and truly loving mathematics.</p>
<p><strong>New articles in this series are posted every Thursday. If you have any suggestions for a specific topic I should write about, please comment it down below!</strong></p>
<hr />
<h1 id="heading-what-even-is-linear-algebra">What Even is Linear Algebra?</h1>
<p><img src="https://images.unsplash.com/photo-1635070041078-e363dbe005cb?ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="math equations" class="image--center mx-auto" /></p>
<p>Linear algebra is a subfield of mathematics that concentrates on linear systems, matrices, and vectors. Through the employment of these three fundamental elements, a multitude of advancements have been achieved in various domains, both within and beyond the sphere of mathematics.</p>
<h2 id="heading-why-havent-i-heard-about-linear-algebra-before">Why Haven't I Heard About Linear Algebra Before?</h2>
<p>If you're still at the beginning of your computer science journey, you might've not been exposed to linear algebra quite yet.</p>
<p>Typically, the first opportunity to take a course in linear algebra is in your 2nd or 3rd year of college. Additionally, colleges usually require you to pass single-variable calculus before being able to enroll in linear algebra.</p>
<p>On top of this, most non-STEM majors in college don't require students to pass any college-level math past single-variable calculus and statistics.</p>
<p>The funny thing is that linear algebra isn't <em>harder</em> than calculus. In fact, A majority of my classmates in university, myself included, believe that linear algebra is a bit <em>easier</em> than calculus.</p>
<p>Also, linear algebra doesn't directly use any tools or concepts from calculus, so you can't even make the argument that you first need to gain prerequisite information from calculus to understand linear algebra.</p>
<p>So if linear algebra isn't harder than calculus, and there's no prerequisite information gained from calculus, then why does it seem so exclusive and "higher level"?</p>
<p>While I don't have an official answer, I have an opinion as to why this is the case.</p>
<p>I believe that it comes down to two main factors:</p>
<ul>
<li><p>Linear algebra's industrial uses are not as widespread as the branches of math that are taught before it</p>
<ul>
<li>While <strong>both</strong> calculus and linear algebra are pretty much only used in STEM and a few other industries (finance, economics, some arts), their uses within those industries are not equal</li>
</ul>
</li>
<li><p>Linear algebra is a "mature" math</p>
<ul>
<li>I know I said that linear algebra is sometimes seen as easier than calculus, but linear algebra's <em>concepts</em> are much more abstract than concepts in single-variable calculus</li>
</ul>
</li>
</ul>
<p>With all that being said, there's no problem with getting a head start on learning linear algebra if you're still in school right now.</p>
<p>And if you're going the self-taught route with computer science, then all the more reason to self-teach the math used in computer science!</p>
<hr />
<h1 id="heading-key-linear-algebra-concepts-used-in-computer-science">Key Linear Algebra Concepts Used in Computer Science</h1>
<p><img src="https://cdn.pixabay.com/photo/2018/09/27/09/22/artificial-intelligence-3706562_1280.jpg" alt="a computer generated image of a human head" class="image--center mx-auto" /></p>
<p>I've carefully curated a list of 9 concepts in linear algebra that are used across various branches of computer science including machine learning, computer graphics, cryptography, image processing, information theory, and much more.</p>
<p>For each of these concepts, I'll provide enough general information so you can understand the big picture, and I'll also mention an example of a branch of computer science that uses the concept.</p>
<p>Also, I ordered the concepts in chronological order to have the concepts build on top of each other and improve the flow of the article.</p>
<p>To not overflow this article with information, I'm going to split this information into two articles. I'll cover the first 5 concepts in this article, and the last 4 concepts in a future article.</p>
<p>For reference, here are all of the 9 concepts that I'll be covering, with the concepts that I'll be covering in this article highlighted in yellow:</p>
<ul>
<li><p><strong><mark>Linear systems</mark></strong></p>
</li>
<li><p><strong><mark>Matrices and Gaussian elimination</mark></strong></p>
</li>
<li><p><strong><mark>Vectors and vector spaces</mark></strong></p>
</li>
<li><p><strong><mark>Vector-matrix multiplication and the Matrix Equation</mark></strong></p>
</li>
<li><p><strong><mark>Transformations</mark></strong></p>
</li>
<li><p><strong>Orthogonality</strong></p>
</li>
<li><p><strong>Determinants</strong></p>
</li>
<li><p><strong>Eigenvalues and eigenvectors</strong></p>
</li>
<li><p><strong>Singular value decomposition</strong></p>
</li>
</ul>
<p>Please keep in mind that I'll only be scratching the surface of all of these concepts. If you're self-teaching linear algebra to pivot into a branch of computer science that uses linear algebra, then I highly recommend <a target="_blank" href="https://amzn.to/3sXB8Ak"><strong>Introduction to Linear Algebra by Gilbert Strang</strong></a><strong>.</strong> This is the same textbook that was used in my college linear algebra course. The structure of the content in this textbook is organized in a well-written format and is easily digestible for self-teaching.</p>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=scrappedscrip-20&amp;language=en_US&amp;marketplace=amazon&amp;region=US&amp;placement=1733146679&amp;asins=1733146679&amp;linkId=6bac7906e0be2e610f9e48ec4d067a1b&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>

<h2 id="heading-i-linear-systems">I. Linear systems</h2>
<p>A linear system can be defined as an assembly of multiple <mark>linear equations</mark> that share a common set of variables. These equations are interconnected, and their solutions are represented by the values of the variables that <mark>simultaneously</mark> satisfy all the equations within the system.</p>
<p>One application of linear systems lies in numerical analysis. Numerical analysis involves utilizing algorithms to find approximate numerical solutions for problems where obtaining the exact numerical solution is either impossible or too complex to resolve.</p>
<h3 id="heading-linear-equations">Linear equations</h3>
<p>A linear equation is an equation that consists of <em>n</em> variables each with a degree of 1.</p>
<p>The general form of a linear equation is:</p>
<p>$$a_1 x_1 + a_2 x_2 + \ldots + a_n x_n = b$$</p><p>The 3 main components of a linear equation are:</p>
<ul>
<li>a set of coefficients</li>
</ul>
<p>$$\{a_1, a_2, \ldots, a_n\}$$</p><ul>
<li>a set of variables</li>
</ul>
<p>$$\{x_1, x_2, \ldots, x_n\}$$</p><ul>
<li>a constant <em>b</em></li>
</ul>
<p>In linear systems of equations, each equation contains the same set of variables but doesn't necessarily have the same set of coefficients.</p>
<p>Putting together a system of <em>m</em> linear equations takes the general form:</p>
<p>$$a_{11} x_1 + a_{12} x_2 + \ldots + a_{1n} x_n = b_1$$</p><p>$$a_{21} x_1 + a_{22} x_2 + \ldots + a_{2n} x_n = b_2$$</p><p>$$\vdots$$</p><p>$$a_{m1} x_1 + a_{m2} x_2 + \ldots + a_{mn} x_n = b_m$$</p><h3 id="heading-simultaneous-solution">Simultaneous solution</h3>
<p><img src="https://cdn.pixabay.com/photo/2017/07/19/16/44/questions-2519654_1280.png" alt="a couple of heads with question marks coming out of them" class="image--center mx-auto" /></p>
<p>The main idea behind a system of equations is that all equations within the system can be solved <em>simultaneously</em>.</p>
<p>By doing so, it becomes possible to find a unique solution, or a set of solutions, that satisfies all the given equations, thereby providing a comprehensive understanding of the problem at hand.</p>
<h2 id="heading-ii-matrices-and-gaussian-elimination">II. Matrices and Gaussian elimination</h2>
<p>As a way to simply store a linear system in a mathematical object that can be operated on, we use a <mark>matrix</mark>. Not only do matrices provide a way to store a linear system, but they simplify the process of being able to solve linear systems through a method called <mark>Gaussian elimination</mark>.</p>
<p>Matrices are found throughout computer science. One of the most common uses of matrices in this field is computer graphics. In animation, for instance, a matrix can be used to define a specific transformation for an object. These matrix transformations enable movement, rotation, and resizing of an object by establishing a new set of coordinates for the object's representation in the animation.</p>
<h3 id="heading-matrices">Matrices</h3>
<p>A matrix is simply an array of numbers arranged into <em>m</em> rows and <em>n</em> columns. Each row in a matrix represents all of the variables' coefficients for each equation, and each column represents all of the coefficients applied to a singular variable in the system.</p>
<p>$$\begin{pmatrix} a &amp; b &amp; c \\ d &amp; e &amp; f \\ g &amp; h &amp; i \end{pmatrix}$$</p><p>The above matrix only contains the coefficients in a linear system. If we wanted to include the linear system's constants in a matrix, the standard notation for doing so is with an augmented matrix:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694496706146/45bcdcd8-1913-4f46-8824-298bdff3bd75.png" alt class="image--center mx-auto" /></p>
<p>In an augmented matrix, the values on the right side of the vertical bar represent the constants in the linear equations. Typically we use augmented matrices when solving linear systems so that we can arrive at a solution that involves the constants in the equations.</p>
<h3 id="heading-gaussian-elimination">Gaussian Elimination</h3>
<p><img src="https://cdn.pixabay.com/photo/2017/10/27/18/38/infographic-2895154_1280.png" alt class="image--center mx-auto" /></p>
<p>One method for solving a linear system involves employing a technique known as Gaussian elimination on a matrix.</p>
<p>Gaussian elimination is essentially an algorithm where you apply row operations to a matrix to reduce the matrix to what's called <em>row echelon form</em>. A matrix is in row echelon form when it satisfies the following conditions:</p>
<ul>
<li><p>All rows filled with all zeros are at the bottom of the matrix</p>
</li>
<li><p>The leading entry (leftmost non-zero entry) of every non-zero filled row is equal to 1</p>
</li>
<li><p>The leading entry of every non-zero filled row is to the right of the leading entry of the row above it</p>
</li>
</ul>
<p>Once a matrix is in row echelon form, you can start to find the values of all the variables using basic algebra.</p>
<p>I know all that seems confusing, but when you see it in practice, it might make some more sense.</p>
<p>Here's an example of applying Gaussian elimination on an augmented matrix to achieve row echelon form:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694499096373/ed40d79a-1f44-4f5e-91b1-02b56ed3b207.png" alt class="image--center mx-auto" /></p>
<p>In the above example, I first chose to multiply all the values in the 1st row by half, since that would make the first entry in the 1st row equal to 1.</p>
<p>For the next row operation, I noticed that the 2nd row's first entry was already 0, meaning my only goal was to make that 7 in the 2nd row turn into a 1. As such, I multiplied the entire row by 1/7.</p>
<p>As you can see, the 3rd row needed some more work than the first two rows.</p>
<p>For the 3rd row, I first added the 1st row's values to it, so that I could turn the first entry into a 0.</p>
<p>My next task was to make the 3rd row's second entry a 0, so I made the 3rd row negative and then added the 2nd row's values multiplied by 1.5.</p>
<p>My last and final step was to simply make the 3rd row's third entry equal to 1, so I just had to multiply the row by -14/41.</p>
<p>As you can see, after applying all of those row operations on the matrix, we end up with a matrix that is in row echelon form.</p>
<p>The resulting matrix doesn't have any zero-filled rows, so we don't have to worry about satisfying the condition that all zero-filled rows are at the bottom of the matrix.</p>
<p>For the other two conditions, the leading entry in each row is equal to 1, and the leading entry in each row is to the right of the leading entry in the row above it.</p>
<p>Now that we have the matrix in row echelon form, we can easily calculate the values of each of the variables using basic algebra.</p>
<p>The 3rd row tells us that the third variable is equal to -36/41.</p>
<p>We can now plug the third variable's value into the 2nd row, and find that the second variable is equal to 19/41.</p>
<p>Finally, we can plug the second variable and third variable's values into the first row, and find that the first variable is equal to 122/41.</p>
<h2 id="heading-iii-vectors-and-vector-spaces">III. Vectors and vector spaces</h2>
<p><img src="https://cdn.pixabay.com/photo/2016/07/18/17/28/electromagnetic-waves-1526374_1280.png" alt class="image--center mx-auto" /></p>
<p>A <mark>vector</mark> is a quantity that is described by both a magnitude and direction. A <mark>vector space</mark> is a set of vectors, where each of the vectors in the vector space follows a defined list of rules. I'll go into more detail about vector spaces further down.</p>
<p>One example of vectors and vector spaces being utilized in computer science is within web information retrieval systems employed by search engines. Vectors are employed to represent webpage documents and search queries. By implementing a vector space model, search engines can provide relevant results in response to a user's search query.</p>
<h3 id="heading-vectors">Vectors</h3>
<p>One of the simplest examples of a vector is a vector from one point to another point on a 2-dimensional plane.</p>
<p>For example, if you have a plot a point <strong><em>A</em></strong> at (0, 0) in the Cartesian coordinate system, and then plot another point <strong><em>B</em></strong> at (4, 6), the vector from <strong><em>A</em></strong> to <em>B</em> would be:</p>
<p>$$\vec{v} = \begin{pmatrix} 4 \\ 6 \end{pmatrix}$$</p><p>Imagine that you're standing on point <strong><em>A</em></strong>, and your friend is at point <strong><em>B</em></strong>, the vector above tells you that you'd need to travel 4 units to the right on the x-axis, followed by 6 units up on the y-axis.</p>
<p>A vector's size is typically described by the dimension of the vector. A vector's dimension is equivalent to the amount of elements in the vector. The vector in the above example is a 2-dimensional vector since it has 2 elements.</p>
<p>A vector can be anything from 0-dimensional to an infinite-dimensional vector.</p>
<p>The dimension of a vector is crucial when determining whether a vector exists within a specific vector space. Before delving into the details of vector spaces, I will first discuss some vector operations and definitions to help you comprehend the concept of vector spaces.</p>
<h3 id="heading-vector-addition">Vector Addition</h3>
<p>If you add a vector to another vector, the result is another vector. For two vectors to be able to be added together, they must be of the same dimension.</p>
<p>When adding two vectors together, you add each element from the first vector to another element in the second vector, based on the element's index in the first vector.</p>
<p>Here's an example of adding two 3-dimensional vectors together:</p>
<p>$$\begin{pmatrix} 4 \\ 6 \\ 1 \end{pmatrix} + \begin{pmatrix} 3 \\ 7 \\ 2 \end{pmatrix} = \begin{pmatrix} 7 \\ 13 \\ 3 \end{pmatrix}$$</p><p>First, I added the 1st element in the first vector to the 1st element in the second vector to obtain the 1st element in the resultant vector (4 + 3 = 7).</p>
<p>Second, I added the 2nd element in the first vector to the 2nd element in the second vector to obtain the 2nd element in the resultant vector (6 + 7 = 13).</p>
<p>Finally, I added the 3rd element in the first vector to the 3rd element in the second vector to obtain the 3rd element in the resultant vector (1 + 2 = 3).</p>
<h3 id="heading-scalar-multiplication">Scalar Multiplication</h3>
<p>Scalar multiplication is the operation of multiplying a vector by a number (effectively scaling the vector). The result of scalar multiplication is another vector.</p>
<p>When multiplying a vector by a scalar, you multiply each element in the vector by the scalar.</p>
<p>Here's an example of multiplying a 4-dimensional vector by a scalar:</p>
<p>$$2 \begin{pmatrix} 4 \\ 8 \\ 0 \\ -2 \end{pmatrix} = \begin{pmatrix} 8 \\ 16 \\ 0 \\-4 \end{pmatrix}$$</p><p>First, I multiplied the 1st element in the vector by the scalar to get the 1st element in the resultant vector (2 * 4 = 8). And then I just repeated this process for the rest of the elements in the vector.</p>
<h3 id="heading-zero-vector">Zero Vector</h3>
<p><img src="https://cdn.pixabay.com/photo/2017/01/15/17/39/number-1982207_1280.png" alt="a metal object is shown in the dark" class="image--center mx-auto" /></p>
<p>The zero vector is simply a vector of any dimension where every element's value is 0.</p>
<p>Typically the zero vector is denoted by the following:</p>
<p>$$\vec{0}$$</p><p>While zero vectors are a very simple concept, they are a requirement of vector spaces, as you'll see below.</p>
<h3 id="heading-vector-spaces">Vector Spaces</h3>
<p>As I stated at the beginning of this section, vector spaces are simply a set of vectors that follow a set of 10 defined rules (or axioms). The rules are as follows:</p>
<p>For each of the 10 axioms below, let <strong><em>V</em></strong> be a vector space over the field of real numbers, let <strong>u</strong>, <strong>v</strong>, and <strong>w</strong> be distinct vectors in vector space <strong><em>V</em></strong>, and let <strong>a</strong> and <strong>b</strong> be distinct real numbers.</p>
<p>$$V \in \mathbb{R}^{n} \; \vert \; \vec{u},\vec{v}, \vec{w} \in V \; \vert \; a, b \in \mathbb{R}$$</p><ol>
<li>Closed under addition</li>
</ol>
<p>$$(\vec{u} + \vec{v}) \in V$$</p><ol>
<li>Commutative under addition</li>
</ol>
<p>$$\vec{u} + \vec{v} = \vec{v} + \vec{u}$$</p><ol>
<li>Associative under addition</li>
</ol>
<p>$$(\vec{u} + \vec{v}) + \vec{w} = \vec{u} + (\vec{v} + \vec{w})$$</p><ol>
<li>Additive identity</li>
</ol>
<p>$$\vec{0} + \vec{u} = \vec{u}$$</p><ol>
<li>Additive inverse</li>
</ol>
<p>$$\vec{u} + -\vec{u} = \vec{0}$$</p><ol>
<li>Closed under scalar multiplication</li>
</ol>
<p>$$a(\vec{u}) \in V$$</p><ol>
<li>Multiplicative identity</li>
</ol>
<p>$$1(\vec{u}) = \vec{u}$$</p><ol>
<li>Associative under scalar multiplication</li>
</ol>
<p>$$(ab)\vec{u} = a(b\vec{u})$$</p><ol>
<li>Distributive property of scalars under scalar multiplication</li>
</ol>
<p>$$a(\vec{u} + \vec{v}) = a\vec{u} + a\vec{v}$$</p><ol>
<li>Distributive property of vectors under scalar multiplication</li>
</ol>
<p>$$(a + b) \vec{u} = a\vec{u} + b\vec{u}$$</p><p>Vector spaces play a crucial role in linear transformations, vector scaling, and various other vector operations, which are essential in the fields of linear algebra and computer science.</p>
<h2 id="heading-iv-vector-matrix-multiplication-and-the-matrix-equation">IV. Vector-matrix multiplication and the Matrix Equation</h2>
<p>One of the operations that we can do on matrices and vectors is by multiplying a matrix by a vector. The result from multiplying a matrix by a vector is another vector, and these 3 components make up what's called a <mark>matrix equation</mark>.</p>
<p>Vector-matrix multiplication is a fundamental operation in data science. For example, multiple linear regression models utilize vector-matrix multiplication to determine a vector of regression coefficients, which helps predict the outcome of a dependent variable within a dataset.</p>
<h3 id="heading-vector-matrix-multiplication">Vector-Matrix multiplication</h3>
<p>For a <em>m</em> x <em>n</em> matrix to be multiplied by a vector, the vector must be <em>m</em>-dimensional. The resulting vector from multiplying a matrix by a vector is <em>n</em>-dimensional.</p>
<p>The steps to multiply a matrix by a vector involve finding the linear combination of the columns of the matrix represented as vectors, where each column's vector is multiplied by a scalar corresponding with an element in the original vector.</p>
<p>Here's an example of multiplying a 2 x 3 matrix by a 3-dimensional vector to get a 2-dimensional vector:</p>
<p>$$\begin{pmatrix} 1 &amp; 4 &amp; 9 \\ 2 &amp; 7 &amp; -3 \end{pmatrix} \begin{pmatrix} 8 \\ -1 \\ 0 \end{pmatrix} = 8 \begin{pmatrix} 1 \\ 2 \end{pmatrix} + -1 \begin{pmatrix} 4 \\ 7 \end{pmatrix} + 0 \begin{pmatrix} 9 \\ -3 \end{pmatrix} = \begin{pmatrix} 4 \\ 9 \end{pmatrix}$$</p><h3 id="heading-the-matrix-equation">The Matrix Equation</h3>
<p>One of the ways to represent a linear system of equations is with a matrix equation:</p>
<p>$$A\vec{x} = \vec{b}$$</p><p>In a matrix equation, <strong><em>A</em></strong> represents a matrix filled with the variables' coefficients in the linear system, <strong>x</strong> represents a vector filled with the variables in the linear system, and <strong>b</strong> represents a vector filled with the constants in the linear system.</p>
<h2 id="heading-v-transformations">V. Transformations</h2>
<p><img src="https://cdn.pixabay.com/photo/2022/04/21/06/11/waves-7146711_1280.jpg" alt="a black background with blue waves on it" class="image--center mx-auto" /></p>
<p>When a vector is operated on and the resulting vector is in a different dimension, then we say that the original vector was transformed. Transformations of vectors are analogous to functions in basic algebra. Since the product of a <em>m</em> x <em>n</em> matrix and a <em>n</em>-dimensional vector results in a <em>m</em>-dimensional vector, we can generally think of matrices as being transformations when applied to vectors. By definition, matrix transformations are <mark>linear transformations</mark>.</p>
<p>One of the most common uses of transformations in computer science is in signal processing. Specifically, there is a particular transformation called the Discrete Fourier Transform, which is used to convert a signal's time vector (or, for example, an image's digital signal vector of pixels) into a signal's frequency vector. This allows for tasks such as image compression, audio editing, and the transmission of digital signals.</p>
<p>A transformation from the <em>n</em>th dimension to the <em>m</em>th dimension is a function that maps an <em>n</em>-dimensional vector to an <em>m</em>-dimensional vector. The general notation for a transformation is:</p>
<p>$$T: \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}$$</p><h3 id="heading-matrices-as-transformations">Matrices as transformations</h3>
<p>Let <strong><em>A</em></strong> be an <em>m</em> x <em>n</em> matrix, and let <strong><em>T</em></strong> represent a transformation.</p>
<p>The matrix transformation by A is then defined as:</p>
<p>$$T(\vec{x}) = A(\vec{x})$$</p><p>This transformation maps the vector <strong>x</strong> to the resultant vector of multiplying the matrix <strong><em>A</em></strong> by the vector <strong>x</strong>.</p>
<h3 id="heading-linear-transformations">Linear transformations</h3>
<p>Linear transformations are simply transformations on a linear combination of vectors. The general definition of a linear transformation is:</p>
<p>Let <strong><em>T</em></strong> be the transformation:</p>
<p>$$T: \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}$$</p><p>Let <strong>u</strong> and <strong>v</strong> be arbitrary vectors such that:</p>
<p>$$\vec{u},\vec{v} \in \mathbb{R}^n \; | \; T(\vec{u}), T(\vec{v}) \in \mathbb{R}^m$$</p><p>Let <strong>a</strong> and <strong>b</strong> be arbitrary scalars such that:</p>
<p>$$a,b \in \mathbb{R}$$</p><p>We can then define <strong><em>T</em></strong> as a linear transformation such that:</p>
<p>$$T(a\vec{u} +b\vec{v}) = aT(\vec{u}) + bT(\vec{v})$$</p><p>By definition, every matrix transformation is a linear transformation.</p>
<p>The main advantage of linear transformations over non-linear transformations is that linear transformations preserve the linearity of the variables. A linear transformation is what allows for vectors to be mapped to another dimension where the same rules of vector operations exist.</p>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this article, I've given a crash course on some of the basic linear algebra concepts used in various branches of computer science.</p>
<p>Although, please keep in mind that I've only scratched the surface of all of these concepts. If you want more in-depth knowledge of these concepts and other concepts in linear algebra, I highly recommend <a target="_blank" href="https://amzn.to/44VFQvs"><strong>Introduction to Linear Algebra by Gilbert Strang</strong></a><strong>.</strong> This is the same textbook that was used in my college linear algebra course. The structure of the content is highly organized and easily digestible for self-teaching.</p>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=scrappedscrip-20&amp;language=en_US&amp;marketplace=amazon&amp;region=US&amp;placement=1733146679&amp;asins=1733146679&amp;linkId=79d8a6d7ff65401f908bb240d971ba6d&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>

<p>Please comment down below if you have any lingering questions or suggestions for an article topic that I should cover in the future.</p>
<p>As stated previously, I'll be covering the rest of the linear algebra concepts (orthogonality, determinants, eigenvalues and eigenvectors, and singular value decomposition) in a future article. To stay up to date and not miss out when I post new articles, make sure to subscribe to my newsletter!</p>
]]></content:encoded></item></channel></rss>