<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Lab 137</title>
<link>https://lab137.org/</link>
<atom:link href="https://lab137.org/index.xml" rel="self" type="application/rss+xml"/>
<description>A blog about stuff</description>
<generator>quarto-1.10.19</generator>
<lastBuildDate>Wed, 07 Jun 2023 18:54:00 GMT</lastBuildDate>
<item>
  <title>Publishing to PyPI</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/publishing-to-pypi/</link>
  <description><![CDATA[ 




<p><em>NOTE: I don’t do this very often so there could be a lot of incorrect information in this post. I’m mainly writing this for myself for future reference. But, if someone else finds this useful then that makes me happy.</em></p>
<p>Publishing to PyPI is an easy way to distribute your code to the masses. It can, however, be a little tricky to get your package uploaded. Here’s how I just did it with my package <a href="https://pypi.org/project/pyautoreloadserver/">PyAutoReloadServer</a>.</p>
<section id="setting-up-your-project" class="level2">
<h2 class="anchored" data-anchor-id="setting-up-your-project">Setting Up Your Project</h2>
<p>However you structure your project, you’ll need something to tell PyPI what’s in your package and how to set the package up. I created a <code>setup.py</code> file for that:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># setup.py</span></span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pathlib</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> setuptools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> setup, find_packages</span>
<span id="cb1-5"></span>
<span id="cb1-6"></span>
<span id="cb1-7">here <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pathlib.Path(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__file__</span>).parent</span>
<span id="cb1-8">readme <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (here <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"README.md"</span>).read_text()</span>
<span id="cb1-9"></span>
<span id="cb1-10">extras_require <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (here <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"requirements.txt"</span>).read_text().splitlines()</span>
<span id="cb1-11"></span>
<span id="cb1-12"></span>
<span id="cb1-13">setup(</span>
<span id="cb1-14">    name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyautoreloadserver"</span>,</span>
<span id="cb1-15">    version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.0.1"</span>,</span>
<span id="cb1-16">    author<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Jay Ess"</span>,</span>
<span id="cb1-17">    description<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A simple HTTP server that reloads when a file change is detected"</span>,</span>
<span id="cb1-18">    url<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/jay3ss/pyautoreloadserver"</span>,</span>
<span id="cb1-19">    long_description<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>readme,</span>
<span id="cb1-20">    long_description_content_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text/markdown"</span>,</span>
<span id="cb1-21">    packages<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>find_packages(),</span>
<span id="cb1-22">    classifiers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb1-23">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Development Status :: 5 - Production/Stable"</span>,</span>
<span id="cb1-24">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Intended Audience :: Developers"</span>,</span>
<span id="cb1-25">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"License :: OSI Approved :: MIT License"</span>,</span>
<span id="cb1-26">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Programming Language :: Python :: 3"</span>,</span>
<span id="cb1-27">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Programming Language :: Python :: 3.11"</span>,</span>
<span id="cb1-28">    ],</span>
<span id="cb1-29">    extras_require<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dev"</span>: extras_require},</span>
<span id="cb1-30">    entry_points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{</span>
<span id="cb1-31">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"console_scripts"</span>: [</span>
<span id="cb1-32">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyautoreloadserver = pyautoreloadserver.cli:main"</span>,</span>
<span id="cb1-33">        ],</span>
<span id="cb1-34">    },</span>
<span id="cb1-35">    package_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{</span>
<span id="cb1-36">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tests"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tests"</span>,</span>
<span id="cb1-37">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyautoreloadserver"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyautoreloadserver"</span>,</span>
<span id="cb1-38">    },</span>
<span id="cb1-39">)</span></code></pre></div></div>
<p>You can read all about what to put in your own <code>setup.py</code> file <a href="https://docs.python.org/3/distutils/setupscript.html">here</a>. I like to use code to keep things like the <code>long_description</code> and <code>extras_require</code> attributes up-to-date automatically. But, you do you.</p>
<p>Now, make an account on <a href="https://pypi.org">PyPI’s website</a> and then get an <a href="https://pypi.org/help#apitoken">API key</a> that you’ll use to upload your package. I made a <code>~/.pypirc</code> file to hold all of the information that I’ll need to upload my packages. Here’s what it looks like (with some info redacted):</p>
<pre class="shell"><code># ~/.pypirc

[distutils]
index-servers =
    pypi
    pypitest

[pypitest]
repository = https://test.pypi.org/legacy/
username = __token__
password = &lt;api-key&gt;

[pypi]
username = __token__
password = &lt;api-key&gt;</code></pre>
<p>There’s couple of things going on in the file above and you should checkout the <a href="https://packaging.python.org/en/latest/specifications/pypirc/">docs</a> for it. But, in the meantime here’s some of the important bits from the docs</p>
<blockquote class="blockquote">
<p>The <code>distutils</code> section defines an <code>index-servers</code> field that lists the name of all sections describing a repository.</p>
<p>Each section describing a repository defines three fields:</p>
<ul>
<li><code>repository</code>: The URL of the repository.</li>
<li><code>username</code>: The registered username on the repository.</li>
<li><code>password</code>: The password that will used to authenticate the username.</li>
</ul>
</blockquote>
<p>The <code>[distutils]</code>’s <code>index-servers</code> field is where you define additional repositories. Note that my <code>~/.pypirc</code> file doesn’t have a <code>repository</code> field for the <code>pypi</code> section. That’s because the default value for that field for the <code>[pypi]</code> section is <code>https://upload.pypi.org/legacy</code>. Also, if you’re using an API token like I am then for the <code>username</code> field you literally put <code>__token__</code> as the value. It took me an embarrassingly long time to figure that one out.</p>
</section>
<section id="building-the-package-for-distribution" class="level2">
<h2 class="anchored" data-anchor-id="building-the-package-for-distribution">Building the Package for Distribution</h2>
<p>There are a multiple ways to build a Python package for distribution. The two that I come across the most are directly using a <code>setup.py</code> script (which is <a href="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html">strongly discouraged</a> and deprecated) or using the <a href="https://pypi.org/project/build/"><code>build</code></a> package. I’m going to use the <code>build</code> package.</p>
<p>I was having trouble using <code>build</code> the command <code>python -m build</code> and had to modify it slightly</p>
<pre class="shell"><code>python -m build --no-isolation --wheel

# this can be simplified by using -n and -w, respectively</code></pre>
<p>which seemed to work. The <code>--no-isolation</code> flag prevents <code>build</code> from using an isolated virtual environment (and makes the build time shorter) and the <code>--wheel</code> flags tells <code>build</code> to create a wheel and a <code>build/</code> and <code>dist/</code> directory.</p>
</section>
<section id="publishing-the-package" class="level2">
<h2 class="anchored" data-anchor-id="publishing-the-package">Publishing the Package</h2>
<p>Next, use <a href="https://twine.readthedocs.io/en/stable/"><code>twine</code></a> to publish the package. Twine is the official PyPI upload tool so it should work for you. You’ll first want to test publishing your package to ensure that everything goes right. Using <code>twine</code> it’s pretty easy to test uploading.</p>
<pre class="shell"><code>python -m twine upload -r pypitest dist/* --verbose</code></pre>
<p>The <code>-r</code> flag tells <code>twine</code> which repository we want to upload to (<code>pypitest</code> here) and then <code>dist/*</code> is the location of the wheel. The <code>--verbose</code> flag gives us more output from <code>twine</code> so if there’s a problem we can have a better idea what it is.</p>
<p>If everything went well go ahead and move on to uploading to PyPI. The command for that is exactly the same as loading to the test PyPI repository, but instead we use the value <code>pypi</code> for the <code>-r</code> flag</p>
<pre class="shell"><code>python -m twine upload -r pypi dist/* --verbose</code></pre>
<p>If nothing went wrong your package should be live on PyPI. Have a question? Leave a comment (if I’ve re-enabled comments) or leave an issue or pull request on the site’s <a href="https://github.com/jay3ss/jay3ss.github.io">repo</a>.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>publishing</category>
  <category>code</category>
  <category>til</category>
  <guid>https://lab137.org/articles/publishing-to-pypi/</guid>
  <pubDate>Wed, 07 Jun 2023 18:54:00 GMT</pubDate>
</item>
<item>
  <title>Viewing Array Contents During Debugging in VS Code</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/viewing-array-contents-during-debugging-in-vs-code/</link>
  <description><![CDATA[ 




<p>After getting annoyed with adding a bunch of array indices to the watch list for a program that I was debugging, I went in search of a better solution. I came across <a href="https://github.com/Microsoft/vscode-cpptools/issues/172">an issue on the VS Code C/C++ Tools GitHub repo</a>. Apparently, you can use the following pattern in the watch list instead</p>
<pre><code>*(int(*)[10])some_pointer</code></pre>
<p>to see the contents of the array <code>some_pointer</code> of type <code>int</code>. Or, basically</p>
<pre><code>*(&lt;type&gt;(*)[arrSize])arrName</code></pre>
<p>Even better, you can use the following</p>
<pre><code>*arrName@arrSize</code></pre>
<p>Here’s a screenshot of doing it manually</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/view_arr_long_way.png" class="img-fluid figure-img"></p>
<figcaption>Manually adding array elements during debug</figcaption>
</figure>
</div>
<p>and here’s a screenshot of using the shortcut</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/view_arr_shortcut.png" class="img-fluid figure-img"></p>
<figcaption>Shortcut of viewing array elements during debug</figcaption>
</figure>
</div>
<p>Much better.</p>



 ]]></description>
  <category>til</category>
  <category>vscode</category>
  <category>debug</category>
  <category>c++</category>
  <guid>https://lab137.org/articles/viewing-array-contents-during-debugging-in-vs-code/</guid>
  <pubDate>Thu, 21 May 2020 02:27:00 GMT</pubDate>
</item>
<item>
  <title>Using SSH with Git Repositories</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/using-ssh-with-git-repositories/</link>
  <description><![CDATA[ 




<p>If you’ve setup your <a href="https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh">git account to use SSH</a>, then should be pretty straightforward. My usual workflow was to <code>git clone</code> the URL of the repository, but I decided to use SSH instead because I was annoyed with having to always enter my credentials. This is how to do it.</p>
<p><em>Note</em>:For the most part, I use GitHub but just replace <code>github.com</code> with whatever service you’re using.</p>
<section id="cloning-a-repository" class="level2">
<h2 class="anchored" data-anchor-id="cloning-a-repository">Cloning a Repository</h2>
<pre><code>git clone git@github.com:&lt;username&gt;/&lt;reponame&gt;.git</code></pre>
</section>
<section id="changing-the-remote-to-use-ssh" class="level2">
<h2 class="anchored" data-anchor-id="changing-the-remote-to-use-ssh">Changing the Remote to Use SSH</h2>
<p>If you’ve already cloned a repo without using SSH, then you can <a href="https://stackoverflow.com/a/11201143/">modify the branch to use SSH</a></p>
<pre><code>git remote set-url origin git@github.com:&lt;username&gt;/&lt;reponame&gt;.git</code></pre>


</section>

 ]]></description>
  <category>til</category>
  <category>git</category>
  <category>ssh</category>
  <guid>https://lab137.org/articles/using-ssh-with-git-repositories/</guid>
  <pubDate>Sat, 02 May 2020 22:11:00 GMT</pubDate>
</item>
<item>
  <title>Converting a PowerPoint PPT to a PDF File</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/converting-a-powerpoint-ppt-to-a-pdf-file/</link>
  <description><![CDATA[ 




<p>I’m currently taking an online class and the professor gives out PowerPoint slides as part of his lecture. I don’t like the LibreOffice version of PowerPoint (Impress) and prefer to use PDF files. So, I found a simple one-liner from <a href="https://askubuntu.com/a/104484">Ask Ubuntu</a> that’s worked well so far.</p>
<pre><code>libreoffice --headless --invisible --convert-to pdf *.ppt</code></pre>



 ]]></description>
  <category>ppt</category>
  <category>powerpoint</category>
  <category>til</category>
  <category>pdf</category>
  <category>convert</category>
  <guid>https://lab137.org/articles/converting-a-powerpoint-ppt-to-a-pdf-file/</guid>
  <pubDate>Fri, 01 May 2020 21:26:00 GMT</pubDate>
</item>
<item>
  <title>How to Print on the Same Line with Python</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/how-to-print-on-the-same-line-with-python/</link>
  <description><![CDATA[ 




<p>Today, I was downloading about 1,600 images and wanted to be able to keep track of how many images I had downloaded so far and what image that I was currently downloading. This is typically very easy with Python, but I decided to print everything on the same line so that I my terminal wouldn’t get cluttered with <code>print</code> statements. This is where I encountered my issue.</p>
<p>The format of the string that I was printing started out as</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\r</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Image</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>, flush<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
<p>where</p>
<ul>
<li><code>\r</code>: is the carriage return which resets the line position to the beginning of the line</li>
<li><code>count</code>: the number of the image that I was downloading</li>
<li><code>end</code>: the character that <code>print</code> will append to the string that it’s printing</li>
<li><code>flush</code>: tells <code>print</code> whether or not it should forcibly flush the stream</li>
</ul>
<p>Basically, what’s going to happen is that when the string is printed it will print the string and put the cursor back at the beginning of the line. If this where done in a loop (probably using <code>time.sleep</code> too), then you’d get the effect of the one line counting up. Neat!</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> count <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>):</span>
<span id="cb2-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\r</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Count</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>, flush<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb2-5">    time.sleep(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>)</span></code></pre></div></div>
<p>We can put this into a function to make it a little easier to read</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> print_same_line(msg):</span>
<span id="cb3-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\r</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, msg, end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>, flush<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, sep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>)</span></code></pre></div></div>
<p>In the function above, we need to use the <code>sep</code> keyword so that when we use this function a space isn’t added between the <code>\r</code> character and our string causing an offset. Now we can use a loop like above and have our code be a bit more readable (we also don’t need the <code>\r</code> character at the beginning of our string).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> count <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>):</span>
<span id="cb4-4">    print_same_line(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Count</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb4-5">    time.sleep(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>)</span></code></pre></div></div>
<p>This worked pretty great, but I encountered trouble when I was reading URLs from a file and was printing them to the terminal.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pathlib</span>
<span id="cb5-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb5-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> urllib.request <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> request</span>
<span id="cb5-4"></span>
<span id="cb5-5">path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pathlib.Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'img'</span>)</span>
<span id="cb5-6">SLEEP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># seconds</span></span>
<span id="cb5-7">urls_file <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'images.txt'</span></span>
<span id="cb5-8"></span>
<span id="cb5-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(urls_file) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> urls:</span>
<span id="cb5-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> count, url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(urls):</span>
<span id="cb5-11">        msg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>.join([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Image'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(count), url.strip()])</span>
<span id="cb5-12">        print_same_line(msg)</span>
<span id="cb5-13"></span>
<span id="cb5-14">        fname <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> url.strip().split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb5-15">        request.urlretrieve(url, path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>fname)</span>
<span id="cb5-16"></span>
<span id="cb5-17">        time.sleep(SLEEP)</span>
<span id="cb5-18"></span>
<span id="cb5-19"></span>
<span id="cb5-20">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Done! Downloaded </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> images'</span>)</span></code></pre></div></div>
<p>which resulted in the unexpected output of</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   1   https://example.com/image-1.jpg</span>
<span id="cb6-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   2   https://example.com/image-2.jpg</span>
<span id="cb6-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   3   https://example.com/image-3.jpg</span>
<span id="cb6-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   4   https://example.com/image-4.jpg</span>
<span id="cb6-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   5   https://example.com/image-5.jpg</span>
<span id="cb6-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Image</span>   6   https://example.com/image-6.jpg</span>
<span id="cb6-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">...</span></span></code></pre></div></div>
<p>It took me longer than I’d like to admit to figure out what went wrong. If you look at the line where I grab the file name (<code>fname</code>) from the URL, you’ll see that I call the <code>strip</code> method. Why? Each line of the file had a <code>\n</code> character at the end of it. Even though I did it for the file name I <strong>did not</strong> do it for the printing of the URL. This one little mistake cost me probably 90 to 120 minutes…</p>
<p>Once I fixed it, however, it worked like a charm. Below is the fixed example</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pathlib</span>
<span id="cb7-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb7-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> urllib.request <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> request</span>
<span id="cb7-4"></span>
<span id="cb7-5"></span>
<span id="cb7-6">path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pathlib.Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'img'</span>)</span>
<span id="cb7-7">SLEEP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># seconds</span></span>
<span id="cb7-8">urls_file <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'images.txt'</span></span>
<span id="cb7-9"></span>
<span id="cb7-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(urls_file) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> urls:</span>
<span id="cb7-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> count, url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(urls):</span>
<span id="cb7-12">        url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> url.strip()</span>
<span id="cb7-13">        print_same_line(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Image</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>url<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb7-14"></span>
<span id="cb7-15">        fname <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> url.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-16">        request.urlretrieve(url, path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>fname)</span>
<span id="cb7-17"></span>
<span id="cb7-18">        time.sleep(SLEEP)</span>
<span id="cb7-19"></span>
<span id="cb7-20"></span>
<span id="cb7-21"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Done! Downloaded </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> images'</span>)</span></code></pre></div></div>



 ]]></description>
  <category>python</category>
  <category>print</category>
  <guid>https://lab137.org/articles/how-to-print-on-the-same-line-with-python/</guid>
  <pubDate>Wed, 18 Dec 2019 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Simple Complex Number Algebra</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/simple-complex-number-algebra/</link>
  <description><![CDATA[ 




<p>I decided to start reviewing some of my controls courses from university to brush up on the fundamentals. While reviewing, I had an “Oh shit” moment when I realized that I’ve forgotten some <em>really</em> basic math. Namely, working with complex numbers. I decided to write this article so that I can easily find a reference if I ever need it (hopefully it helps you too). (BIG thanks to Dr. Tabrizi for putting together notes that are very comprehensible.)</p>
<section id="general-form-of-a-complex-number" class="level2">
<h2 class="anchored" data-anchor-id="general-form-of-a-complex-number">General Form of a Complex Number</h2>
<!-- Check the link -->
<p>According to Wikipedia, <a href="https://en.wikipedia.org/wiki/Complex_number" title="Wikipedia - Complex Numbers">complex numbers</a> are</p>
<blockquote class="blockquote">
<p>[…] regarded in the mathematical sciences as just as “real” as the real numbers, and are fundamental in many aspects of the scientific description of the natural world.</p>
</blockquote>
<p>Complex numbers can be written in two forms: rectangular and polar. They live in the 2-dimensional complex plane with the horizontal axis is called the “real” axis while the vertical axis is called the “imaginary” axis. The figure below shows this nicely.</p>
<figure class="image figure">
<img src="https://lab137.org/articles/img/complex_number_rect.svg" class="img-responsive align-center figure-img" alt="A complex number" title="A complex number">
<figcaption>
A complex number z, as a point (red) and its position vector (blue). Image courtesy of <cite> <a href="https://en.wikipedia.org/wiki/Complex_number#/media/File:A_plus_bi.svg"> LasinIkamusumeFan </a> under the <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en"> Creative Commons 4.0 License </a>. </cite>
</figcaption>
</figure>
<p><strong>Note</strong> that in electrical engineering <img src="https://latex.codecogs.com/png.latex?j"> denotes the imaginary number/axis so as to avoid confusion with the time-varying current <img src="https://latex.codecogs.com/png.latex?i">. This is the notation that I’ll be using throughout this article. If this confuses you, then just replace every instance of <img src="https://latex.codecogs.com/png.latex?j"> with <img src="https://latex.codecogs.com/png.latex?i">.</p>
<section id="rectangular-form" class="level3">
<h3 class="anchored" data-anchor-id="rectangular-form">Rectangular Form</h3>
<p>The rectangular form of a complex number is as follows</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Az%20=%20a%20+%20jb.%0A"></p>
<p>The letters <img src="https://latex.codecogs.com/png.latex?a"> and <img src="https://latex.codecogs.com/png.latex?b"> are referred to as the real and imaginary components of the complex number <img src="https://latex.codecogs.com/png.latex?z">, respectively. In the figure above, <img src="https://latex.codecogs.com/png.latex?a"> is the horizontal axis while <img src="https://latex.codecogs.com/png.latex?b"> is the vertical axis.</p>
<p>You may sometimes see <img src="https://latex.codecogs.com/png.latex?Re(z)"> and <img src="https://latex.codecogs.com/png.latex?Im(z)"> to mean the real and imaginary components of the complex number <img src="https://latex.codecogs.com/png.latex?z">, respectively.</p>
</section>
<section id="polar-form" class="level3">
<h3 class="anchored" data-anchor-id="polar-form">Polar Form</h3>
<p>The rectangular form of a complex number is as follows</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Az%20=%20%5C%7Cr%5C%7C%20e%5E%7Bj%5Cphi%7D.%0A"></p>
<p>and is shown in the figure below.</p>
<figure class="image figure">
<img src="https://lab137.org/articles/img/complex_number_polar_opt.svg" alt="A complex number" title="A complex number" class="center responsive-image figure-img">
<figcaption>
A complex number z, as a point (red) and its position vector (blue). Image courtesy of <cite> <a href="https://en.wikipedia.org/wiki/File:Complex_number_illustration_modarg.svg"> Oleg Alexandrov </a> under the <a href="https://creativecommons.org/licenses/by-sa/3.0/deed.en"> Creative Commons 3.0 License </a>. </cite>
</figcaption>
</figure>
<p><img src="https://latex.codecogs.com/png.latex?%5C%7Cr%5C%7C"> is the <em>magnitude</em> and <img src="https://latex.codecogs.com/png.latex?%5Cphi"> is the <em>phase angle</em> of the complex number <img src="https://latex.codecogs.com/png.latex?z">, respectively. To help explain this, you can think of a complex number as a vector in the complex plane with the magnitude being the length of the vector and the phase angle the direction.</p>
</section>
</section>
<section id="converting-between-forms" class="level2">
<h2 class="anchored" data-anchor-id="converting-between-forms">Converting Between Forms</h2>
<p>It’s often useful (or necessary) to convert from one form to another to either get information (such as magnitude) or to aid in calculations (adding complex numbers is easier when both numbers are in rectangular form).</p>
<section id="converting-from-polar-to-rectangular-form" class="level3">
<h3 class="anchored" data-anchor-id="converting-from-polar-to-rectangular-form">Converting From Polar to Rectangular Form</h3>
<p>To convert from polar to rectangular form, we will use Euler’s formula and multiply the result by the magnitude <img src="https://latex.codecogs.com/png.latex?%5C%7Cr%5C%7C">.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0A%20%20%20%20z%20&amp;=%20%5C%7Cr%5C%7C%5Cleft(%5Ccos%20%5Cphi%20+%20j%20%5Csin%20%5Cphi%20%5Cright)%20%5Cnonumber%20%5C%5C%0A%20%20%20%20%20%20&amp;=%20a%20+%20jb%20%5Clabel%7Beq:polar_to_rect%7D%0A%5Cend%7Balign%7D%0A"></p>
</div>
<p><em>Interesting side note: Euler made discoveries in so many different fields that it started getting to the point that there were too many discoveries/theorems being named after him, so</em></p>
<blockquote class="blockquote">
<p>[in] an effort to avoid naming everything after Euler, some discoveries and theorems are attributed to the first person to have proved them <em>after</em> Euler. <sup>1<sup></sup></sup></p>
</blockquote>
<section id="example" class="level4">
<h4 class="anchored" data-anchor-id="example">Example</h4>
<p>It usually helps to make everything clear by having examples. So, let’s see how the conversion from polar to rectangular form actually works.</p>
<p>Let <img src="https://latex.codecogs.com/png.latex?z%20=%202%20%5Csqrt%7B2%7D%20%5C,%20e%5E%7Bj%20%5C,%20%5Cfrac%7B%5Cpi%7D%7B4%7D%7D">.</p>
<p>The first thing that we have to do is identify the magnitude and phase angle. Here, the magnitude is <img src="https://latex.codecogs.com/png.latex?%5C%7Cr%5C%7C%20=%202%20%5Csqrt%7B2%7D"> and the phase angle is <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20%5Cfrac%7B%5Cpi%7D%7B4%7D">. Now, it’s just a matter of plugging everything in to Equation <img src="https://latex.codecogs.com/png.latex?%5Cref%7Beq:polar_to_rect%7D">.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20a%20+%20jb%20&amp;=%20%5C%7Cr%5C%7C%20%5Cleft(%5Ccos%20%5Cphi%20+%20j%20%5Csin%20%5Cphi%20%5Cright)%20%5C%5C%0A%20%20%20%20&amp;=%202%20%5Csqrt%7B2%7D%20%5Cleft(%5Ccos%20%5Cfrac%7B%5Cpi%7D%7B4%7D%20+%20j%20%5Csin%20%5Cfrac%7B%5Cpi%7D%7B4%7D%20%5Cright)%20%5C%5C%0A%20%20%20%20&amp;=%202%20%5Csqrt%7B2%7D%20%5Cleft(%5Cfrac%7B%5Csqrt%7B2%7D%7D%7B2%7D%20+%20j%20%5Cfrac%7B%5Csqrt%7B2%7D%7D%7B2%7D%20%5Cright)%20%5C%5C%0A%20%20%20%20&amp;=%20%5Cboxed%7B2%20+%20j2%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
</section>
</section>
<section id="converting-from-rectangular-to-polar-form" class="level3">
<h3 class="anchored" data-anchor-id="converting-from-rectangular-to-polar-form">Converting from Rectangular to Polar Form</h3>
<p>To convert from rectangular to polar form, we will need to find the magnitude and the phase angle of the complex number. To find the magnitude of <img src="https://latex.codecogs.com/png.latex?z">, we will use the formula for the [Euclidean norm] (also known as the modulus, or norm)</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bequation%7D%0A%20%20%20%20%5C%7Cr%5C%7C%20=%20%5Csqrt%7Ba%5E2%20+%20b%5E2%7D.%0A%20%20%20%20%5Clabel%7Beq:euclidean_norm%7D%0A%5Cend%7Bequation%7D%0A"></p>
</div>
<p>Finding the phase angle can be a little bit tricky (which is what prompted me to write this article). Although you may be tempted to immediately use <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7Bb%7D%7Ba%7D%7D">, you will quickly run into trouble. This equation only works for the <em>first</em> quadrant. Therefore, you must determine which quadrant the complex number is in, which is the tricky part. Luckily, the table below shows you exactly how to find this out.</p>
<!--
    IMPORTANT! Don't remove the space in front of the div! It'll cause MathJax
    to stop rendering in the table
-->
<div class="table-container">
<table class="table is-fullwidth">
<thead>
<tr>
<th>
Conditions
</th>
<th>
Quadrant
</th>
<th>
Range of ()
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
(a ,) and (b )
</td>
<td>
1<sup>st</sup> quadrant
</td>
<td>
0° () 90°
</td>
</tr>
<tr>
<td>
(a ,) and (b )
</td>
<td>
2<sup>nd</sup> quadrant
</td>
<td>
90° () 180°
</td>
</tr>
<tr>
<td>
(a ,) and (b )
</td>
<td>
3<sup>rd</sup> quadrant
</td>
<td>
180° () 270°
</td>
</tr>
<tr>
<td>
a (,) and b ()
</td>
<td>
4<sup>th</sup> quadrant
</td>
<td>
270° () 360°
</td>
</tr>
</tbody>
</table>
</div>
<p>Once you know what quadrant the complex number is in, then finding the phase angle is pretty straightforward. Below I’ve created another table that lists the formula that you need to use to find the (numerical) phase angle dependent on the quadrant.</p>
<!--
    IMPORTANT! Don't remove the space in front of the table! It'll cause MathJax
    to stop rendering in the table
-->
<div class="table-container">
<table class="table is-hoverable">
<thead>
<tr>
<th>
Quadrant
</th>
<th>
Formula
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1<sup>st</sup> quadrant
</td>
<td>
(= ^{-1}{})
</td>
</tr>
<tr>
<td>
2<sup>nd</sup> quadrant
</td>
<td>
(= - ^{-1}{})
</td>
</tr>
<tr>
<td>
3<sup>rd</sup> quadrant
</td>
<td>
(= + ^{-1}{||})
</td>
</tr>
<tr>
<td>
4<sup>th</sup> quadrant
</td>
<td>
(= -^{-1}{})
</td>
</tr>
</tbody>
</table>
</div>
<section id="example-1" class="level4">
<h4 class="anchored" data-anchor-id="example-1">Example</h4>
<p>Let’s convert <img src="https://latex.codecogs.com/png.latex?z%20=%20%5Cpm%203%20%5Cpm%20j3"> to polar form.</p>
<section id="first-quadrant" class="level5">
<h5 class="anchored" data-anchor-id="first-quadrant">First Quadrant</h5>
<p>Let’s first do <img src="https://latex.codecogs.com/png.latex?z%20=%203%20+%20j3">. It’s very simple to find the magnitude so let’s do that first.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5C%7Cr%5C%7C%20&amp;=%20%5Csqrt%7Ba%5E2%20+%20b%5E2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Csqrt%7B3%5E2%20+%203%5E2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Csqrt%7B18%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B3%20%5Csqrt%7B2%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>We can tell that this number is in the first quadrant because both of the real and imaginary components are positive. Therefore, according to the above table, we will use <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7Bb%7D%7Ba%7D%7D"> to find the phase angle.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5Cphi%20&amp;=%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7Bb%7D%7Ba%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7B3%7D%7B3%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B%5Cfrac%7B%5Cpi%7D%7B4%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>Combining the magnitude and phase leaves us with the polar form</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cboxed%7Bz%20=%203%20%5Csqrt%7B2%7D%20%5C,%20e%20%5C,%20%5E%7Bj%20%5Cfrac%7B%5Cpi%7D%7B4%7D%7D%7D%0A"></p>
</div>
</section>
<section id="second-quadrant" class="level5">
<h5 class="anchored" data-anchor-id="second-quadrant">Second Quadrant</h5>
<p>Now, let’s do <img src="https://latex.codecogs.com/png.latex?z%20=%20-3%20+%20j3">. Again, we’re going to find the magnitude first.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5C%7Cr%5C%7C%20&amp;=%20%5Csqrt%7B%5Cleft(-3%20%5Cright)%5E2%20+%203%5E2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Csqrt%7B18%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B3%20%5Csqrt%7B2%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>We can tell that this number is in the second quadrant because the real component is negative while the imaginary component is positive. Therefore, according to the above table, we will use <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20%5Cpi%20-%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7Bb%7D%7B%5Cleft%7Ca%5Cright%7C%7D%7D"> to find the phase angle.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5Cphi%20&amp;=%20%5Cpi%20-%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7Bb%7D%7B%5Cleft%7Ca%5Cright%7C%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cpi%20-%20%5Ctan%5E%7B-1%7D%7B%5Cfrac%7B3%7D%7B%5Cleft%7C-3%5Cright%7C%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cpi%20-%20%5Cfrac%7B%5Cpi%7D%7B4%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B%5Cfrac%7B3%5Cpi%7D%7B4%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>Combining the magnitude and phase leaves us with the polar form</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cboxed%7Bz%20=%203%20%5Csqrt%7B2%7D%20%5C,%20e%20%5C,%20%5E%7Bj%20%5Cfrac%7B3%5Cpi%7D%7B4%7D%7D%7D%0A"></p>
</div>
</section>
<section id="third-quadrant" class="level5">
<h5 class="anchored" data-anchor-id="third-quadrant">Third Quadrant</h5>
<p>Now, let’s do <img src="https://latex.codecogs.com/png.latex?z%20=%20-3%20-%20j3">. Again, we’re going to find the magnitude first.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5C%7Cr%5C%7C%20&amp;=%20%5Csqrt%7B%5Cleft(-3%20%5Cright)%5E2%20+%20%5Cleft(-3%20%5Cright)%5E2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Csqrt%7B18%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B3%20%5Csqrt%7B2%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>We can tell that this number is in the third quadrant because both of the real and imaginary components are negative. Therefore, according to the above table, we will use <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20%5Cpi%20+%20%5Ctan%5E%7B-1%7D%7B%5Cleft%7C%5Cfrac%7Bb%7D%7Ba%7D%5Cright%7C%7D"> to find the phase angle.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5Cphi%20&amp;=%20%5Cpi%20+%20%5Ctan%5E%7B-1%7D%7B%5Cleft%7C%5Cfrac%7Bb%7D%7Ba%7D%5Cright%7C%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cpi%20+%20%5Ctan%5E%7B-1%7D%7B%5Cleft%7C%5Cfrac%7B-3%7D%7B-3%7D%5Cright%7C%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cpi%20+%20%5Cfrac%7B%5Cpi%7D%7B4%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B%5Cfrac%7B5%5Cpi%7D%7B4%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>Combining the magnitude and phase leaves us with the polar form</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cboxed%7Bz%20=%203%20%5Csqrt%7B2%7D%20%5C,%20e%20%5C,%20%5E%7Bj%20%5Cfrac%7B5%5Cpi%7D%7B4%7D%7D%7D%0A"></p>
</div>
</section>
<section id="fourth-quadrant" class="level5">
<h5 class="anchored" data-anchor-id="fourth-quadrant">Fourth Quadrant</h5>
<p>Now, let’s do <img src="https://latex.codecogs.com/png.latex?z%20=%203%20-%20j3">. Again, we’re going to find the magnitude first.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5C%7Cr%5C%7C%20&amp;=%20%5Csqrt%7B3%5E2%20+%20%5Cleft(-3%20%5Cright)%5E2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Csqrt%7B18%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B3%20%5Csqrt%7B2%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>We can tell that this number is in the fourth quadrant because real component is positive and the imaginary component is negative. Therefore, according to the above table, we will use <img src="https://latex.codecogs.com/png.latex?%5Cphi%20=%20-%5Ctan%5E%7B-1%7D%7B%5Cfrac%7B%5Cleft%7Cb%5Cright%7C%7D%7Ba%7D%7D"> to find the phase angle.</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20%5Cphi%20&amp;=%20-%5Ctan%5E%7B-1%7D%7B%5Cfrac%7B%5Cleft%7Cb%5Cright%7C%7D%7Ba%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20-%5Ctan%5E%7B-1%7D%7B%5Cfrac%7B%5Cleft%7C-3%5Cright%7C%7D%7B-3%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20%20&amp;=%20%5Cboxed%7B-%5Cfrac%7B%5Cpi%7D%7B4%7D%7D%0A%5Cend%7Balign*%7D%0A"></p>
</div>
<p>Combining the magnitude and phase leaves us with the polar form</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cboxed%7Bz%20=%203%20%5Csqrt%7B2%7D%20%5C,%20e%20%5C,%20%5E%7B-j%20%5Cfrac%7B%5Cpi%7D%7B4%7D%7D%7D%0A"></p>
</div>
</section>
</section>
</section>
</section>
<section id="arithmetic-operations" class="level2">
<h2 class="anchored" data-anchor-id="arithmetic-operations">Arithmetic Operations</h2>
<p>Now that we know how to convert from one form to another, we can perform arithmetic operations with complex numbers.</p>
<section id="addition" class="level3">
<h3 class="anchored" data-anchor-id="addition">Addition</h3>
<p>It’s easiest to add and subtract complex numbers when they’re in <em>rectangular</em> form. So, the first thing to do is to convert all of the complex numbers to rectangular form if necessary. Then, you simply add the components together.</p>
<p>For example, suppose that you have two complex numbers <img src="https://latex.codecogs.com/png.latex?z_1%20=%20a_1%20+%20jb_1"> and <img src="https://latex.codecogs.com/png.latex?z_2%20=%20a_2%20+%20jb_2">. To get the new number <img src="https://latex.codecogs.com/png.latex?z_3%20=%20z_1%20+%20z_2">, you would do the following</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20z_3%20&amp;=%20z_1%20+%20z_2%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(a_1%20+%20jb_1%20%5Cright)%20+%20%5Cleft(a_2%20+%20jb_2%20%5Cright)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(a_1%20+%20a_2%20%5Cright)%20+%20j%5Cleft(b_1%20+%20b_2%20%5Cright)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20a_3%20+%20jb_3.%0A%5Cend%7Balign*%7D%0A"></p>
</div>
</section>
<section id="subtraction" class="level3">
<h3 class="anchored" data-anchor-id="subtraction">Subtraction</h3>
<p>Subtraction works similarly to addition (just like with real numbers). First, we should make sure that all complex numbers are in rectangular form. Then, we can simply subtract the components of each complex number.</p>
<p>For example, suppose that you have two complex numbers <img src="https://latex.codecogs.com/png.latex?z_1%20=%20a_1%20+%20jb_1"> and <img src="https://latex.codecogs.com/png.latex?z_2%20=%20a_2%20+%20jb_2">. To get the new number <img src="https://latex.codecogs.com/png.latex?z_3%20=%20z_1%20+%20z_2"> you would do the following</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%20%20%20%20z_3%20&amp;=%20z_1%20-%20z_2%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(a_1%20+%20jb_1%20%5Cright)%20-%20%5Cleft(a_2%20+%20jb_2%20%5Cright)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(a_1%20-%20a_2%20%5Cright)%20+%20j%5Cleft(b_1%20-%20b_2%20%5Cright)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20a_3%20+%20jb_3.%0A%5Cend%7Balign*%7D%0A"></p>
</div>
</section>
<section id="multiplication" class="level3">
<h3 class="anchored" data-anchor-id="multiplication">Multiplication</h3>
<p>In contrast to addition and subtraction, multiplication of complex numbers is more easily performed when all complex numbers are in <em>polar</em> form.</p>
<p>The first thing to do when multiplying complex numbers is to make sure to convert all of them into polar form. Next, we multiply the magnitudes and then add the phase angles.</p>
<p>For example, suppose that we have two complex numbers <img src="https://latex.codecogs.com/png.latex?z_1%20=%20r_1%20%5C,%20e%5E%7Bj%20%5Cphi_1%7D"> and <img src="https://latex.codecogs.com/png.latex?z_2%20=%20r_2%20%5C,%20e%5E%7Bj%20%5Cphi_2%7D"> and we want to multiply them. To multiply them, you would do the following</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0A%20%20%20%20z_3%20&amp;=%20z_1%20%5Ccdot%20z_2%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(r_1%20%5C,%20e%5E%7Bj%20%5Cphi_1%7D%20%5Cright)%20%5Ccdot%20%5Cleft(r_2%20%5C,%20e%5E%7Bj%20%5Cphi_2%7D%20%5Cright)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cleft(r_1%20%5Ccdot%20r_2%20%5Cright)%20%5C,%20e%5E%7B%5Cleft(%5Cphi_1%20+%20%5Cphi_2%20%5Cright)%7D.%0A%5Cend%7Balign%7D%0A"></p>
</div>
</section>
<section id="division" class="level3">
<h3 class="anchored" data-anchor-id="division">Division</h3>
<p>Like multiplication, division of complex numbers is easiest when all of the complex numbers are in polar form. So, first convert all of the complex numbers to polar form, then divide the magnitudes and <em>subtract</em> the phase angles.</p>
<p>For example, suppose that we have two complex numbers <img src="https://latex.codecogs.com/png.latex?z_1%20=%20r_1%20%5C,%20e%5E%7Bj%20%5Cphi_1%7D"> and <img src="https://latex.codecogs.com/png.latex?z_2%20=%20r_2%20%5C,%20e%5E%7Bj%20%5Cphi_2%7D"> and we want to multiply them. To multiply them, you would do the following</p>
<div class="math-block">
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0A%20%20%20%20z_3%20&amp;=%20%5Cfrac%7Bz_1%7D%7Bz_2%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cfrac%7Br_1%20%5C,%20e%5E%7Bj%20%5Cphi_1%7D%7D%7Br_2%20%5C,%20e%5E%7Bj%20%5Cphi_2%7D%7D%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Cfrac%7Br_1%7D%7Br_2%7D%20%5C,%20e%5E%7B%5Cleft(%5Cphi_1%20-%20%5Cphi_2%20%5Cright)%7D.%0A%5Cend%7Balign%7D%0A"></p>
</div>
</section>
</section>
<section id="complex-conjugate" class="level2">
<h2 class="anchored" data-anchor-id="complex-conjugate">Complex Conjugate</h2>
<p>Every complex number has a complex conjugate and that conjugate is found by switching the signs of the imaginary component. For example, if we have a complex number <img src="https://latex.codecogs.com/png.latex?z%20=%20a%20+%20jb"> then its complex conjugate is <img src="https://latex.codecogs.com/png.latex?z%5E*%20=%20a%20-%20jb">. Notice how only the sign of the imaginary component became negative and the real component’s sign remained the same. Because we’re just switching signs of the imaginary component, you can think of the complex conjugate as a reflection about the real axis. Also note the <img src="https://latex.codecogs.com/png.latex?%5E*"> next to the variable <img src="https://latex.codecogs.com/png.latex?z">. This is one of the notations to denote a complex conjugate.</p>
<p>Complex conjugates are very important in math, physics, and engineering and you should definitely read about the <a href="https://www.allaboutcircuits.com/technical-articles/importance-of-complex-conjugates/" title="All About Circuits - The Importance of Complex Conjugates">importance of complex conjugates</a>.</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this article, we learned about the different forms of a complex number and how to convert between them. We also learned how to add, subtract, multiply, and divide complex numbers. Finally, we learned how to find the complex conjugate of a complex number as well. If you have any comments or questions, please comment below.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references"><a name="refs"></a>References</h2>
<ol type="1">
<li><a href="https://en.wikipedia.org/wiki/List_of_things_named_after_Leonhard_Euler" title="Wikipedia - List of things named after Leonhard Euler">Wikipedia - List of things named after Leonhard Euler</a></li>
</ol>
<!-- Links -->


</section>

 ]]></description>
  <category>complex numbers</category>
  <category>math</category>
  <category>algebra</category>
  <category>complex conjugate</category>
  <category>imaginary numbers</category>
  <guid>https://lab137.org/articles/simple-complex-number-algebra/</guid>
  <pubDate>Fri, 19 Jul 2019 23:00:00 GMT</pubDate>
</item>
<item>
  <title>C++: Simple Structs Usage</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/c-simple-structs-usage/</link>
  <description><![CDATA[ 




<p>Similar to arrays, structs allow you to hold a group of data. structs allow you to group together related members that would be awkwardly expressed as multiple arrays (e.g., the x- and y-coordinates of a pixel or the name, address, and telephone number of a person) into one convenient unit.</p>
<p>Not only do structs group data, they’re also easy to define and use.</p>
<section id="declaring-a-struct" class="level2">
<h2 class="anchored" data-anchor-id="declaring-a-struct">Declaring a Struct</h2>
<p>The example below shows the semantics of declaring a struct. Just replace whatever is inside of the <code>&lt;...&gt;</code> with the appropriate text.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>tag<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb1-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>member<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;;</span></span>
<span id="cb1-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// more declarations...</span></span>
<span id="cb1-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// notice the semicolon</span></span></code></pre></div></div>
<p>For example</p>
<ul>
<li><code>&lt;tag&gt;</code>: is the name of the struct, so <code>Student</code></li>
<li><code>&lt;data-type&gt;</code>: is the data type of the member (variable), so <code>int</code></li>
<li><code>&lt;member-name&gt;</code>: is the name of the member (variable), so <code>id</code></li>
</ul>
<p>Put it all together (plus some additional members) and we have</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Student</span>
<span id="cb2-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-3">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Student's ID number</span></span>
<span id="cb2-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>string name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Student's name</span></span>
<span id="cb2-5">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float</span> gpa<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Student's GPA</span></span>
<span id="cb2-6">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> gradeLevel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Students current grade level (e.g., 11)</span></span>
<span id="cb2-7"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span></code></pre></div></div>
<p>Notice how I left the tag (<code>Student</code>) capitalized? I like to do that so when I’m reading my code I can easily spot the declaration of a struct. This <code>Student</code> struct is basically a new data type and we can use it as such.</p>
</section>
<section id="defining-a-struct-variable" class="level2">
<h2 class="anchored" data-anchor-id="defining-a-struct-variable">Defining a Struct Variable</h2>
<p>It’s no different defining a variable of type <code>Student</code> than it is of <code>int</code> or <code>double</code>. For example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb3-1">Student student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>We just declared a variable named <code>student</code> with the type of <code>Student</code>. Simple!</p>
<section id="initialization-lists" class="level3">
<h3 class="anchored" data-anchor-id="initialization-lists">Initialization Lists</h3>
<p>You can also use an initialization list to when defining a struct.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb4-1">Student student <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5678</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A. Student"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span></code></pre></div></div>
<p>You don’t have to provide an initializer for each member of the struct, but you can’t skip any either. That means that if you skip initializing one member then you must leave all of the members that follow it uninitialized as well.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb5-1">Student stu1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6789</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Billy"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// works</span></span>
<span id="cb5-2">Student stu2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6789</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// does not work, skipped "name"</span></span></code></pre></div></div>
</section>
</section>
<section id="using-a-struct" class="level2">
<h2 class="anchored" data-anchor-id="using-a-struct">Using a Struct</h2>
<p>We use the dot (<code>.</code>) operator to set and access the members of a struct like below</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb6-1">Student johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-2">johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1234</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-3">johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Johnny B. Goode"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-4">johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>gpa <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-5">johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>gradeLevel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-6"></span>
<span id="cb6-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Student johnny = {1234, "Johnny B. Goode", 1.1, 7} // also works</span></span>
<span id="cb6-8"></span>
<span id="cb6-9"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ID:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb6-10">          <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Name:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb6-11">          <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"GPA:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>gpa <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb6-12">          <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Grade Level:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> johnny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>gradeLevel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>After we compile and run this, the output will be</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb7-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ID:</span>             1234</span>
<span id="cb7-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name:</span>           Johnny B. Goode</span>
<span id="cb7-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">GPA:</span>            1.1</span>
<span id="cb7-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Grade</span> Level:    7</span></code></pre></div></div>
<p>This may seem like a lot of work, but its usefulness becomes immediately clear when we have multiple students.</p>
</section>
<section id="array-of-structs" class="level2">
<h2 class="anchored" data-anchor-id="array-of-structs">Array of Structs</h2>
<p>Instead of having to declare multiple arrays (or vectors) or variables we can declare an array (or vector) of type <code>Student</code> and use a loop to set or access the members of each element of the array (or vector). For example</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb8-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// const int NUMBER_OF_STUDENTS = &lt;pick a number&gt;;</span></span>
<span id="cb8-2">Student students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>NUMBER_OF_STUDENTS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">];</span></span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Set the member for each element of the array</span></span>
<span id="cb8-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> NUMBER_OF_STUDENTS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++)</span></span>
<span id="cb8-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-7">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Enter student ID: "</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-8">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-9">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>ignore<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span>
<span id="cb8-10"></span>
<span id="cb8-11">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Enter student name: "</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-12">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>getline<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span>
<span id="cb8-13"></span>
<span id="cb8-14">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Enter student GPA: "</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-15">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>gpa<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-16"></span>
<span id="cb8-17">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Enter student grade level: "</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-18">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>gradeLevel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-19"></span>
<span id="cb8-20">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>endl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-21"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-22"></span>
<span id="cb8-23"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Print out the member for each element of the array</span></span>
<span id="cb8-24"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> NUMBER_OF_STUDENTS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++)</span></span>
<span id="cb8-25"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-26">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Student #"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb8-27">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ID:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb8-28">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Name:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb8-29">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"GPA:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>gpa <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb8-30">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Grade Level:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> students<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">].</span>gradeLevel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-31"></span>
<span id="cb8-32">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>endl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-33"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
</section>
<section id="pointer-to-structs" class="level2">
<h2 class="anchored" data-anchor-id="pointer-to-structs">Pointer to Structs</h2>
<p>You define a pointer to a struct in the exact same way that you’d define a pointer to any other data type</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb9-1">Student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Using a pointer to a struct is a <em>little</em> bit more involved. If you need to use a pointer to a struct then you have a couple of options with one of them being <em>much</em> easier and the preferred way.</p>
<section id="dereferencing" class="level3">
<h3 class="anchored" data-anchor-id="dereferencing">Dereferencing</h3>
<p>I’m going to start with the awkward notation first. To dereference a pointer you use the star (<code>*</code>) operator just like any other pointer. However, if you want to access the member of a pointer to a struct you’d <em>think</em> that the <code>*</code> operator would be all that’s necessary</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb10-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>The above should print out the string that’s at <code>name</code>, right? Wrong! You’re actually trying to dereference <code>student.name</code> <em>not</em> <code>student</code>. The <code>.</code> operator has a higher precedence than <code>*</code> so you need to use parentheses to give the <code>*</code> higher precedence.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb11-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(*</span>student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">).</span>name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p><strong>Now</strong> we’ll print out the <code>name</code>. This is very awkward and can actually be confusing too. This is why the arrow notation is better.</p>
</section>
<section id="arrow-notation" class="level3">
<h3 class="anchored" data-anchor-id="arrow-notation">Arrow Notation</h3>
<p>Instead of using the clumsy dereferencing notation we’re going to prefer using the arrow operator (<code>-&gt;</code>). As you’ll see, it’s very similar to the dot notation</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb12-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>cout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span> student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>This is much easier on the eyes.</p>
</section>
</section>
<section id="array-members" class="level2">
<h2 class="anchored" data-anchor-id="array-members">Array Members</h2>
<p>Structs can have an array as a member, but you have to take care of how you define them. Member arrays must have their lengths defined in the definition of the struct <em>unless</em> it’s the last member of the struct [1]. For example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb13-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Will compile, flexible length member array declared</span></span>
<span id="cb13-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// as last member</span></span>
<span id="cb13-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Testing1</span>
<span id="cb13-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb13-5">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> number<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb13-6">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> numbers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[];</span></span>
<span id="cb13-7"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span>
<span id="cb13-8"></span>
<span id="cb13-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Won't compile, member array length not declared</span></span>
<span id="cb13-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Testing2</span>
<span id="cb13-11"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb13-12">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> numbers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[];</span></span>
<span id="cb13-13">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> number<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb13-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb13-15"></span>
<span id="cb13-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Will compile, member array length declared</span></span>
<span id="cb13-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Testing3</span>
<span id="cb13-18"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb13-19">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> numbers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">];</span></span>
<span id="cb13-20">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> number<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb13-21"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span></code></pre></div></div>
<p>To use an array member, you use it just like any other array</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb14-1">Testing3 testing<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb14-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++)</span></span>
<span id="cb14-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb14-4">    testing<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>numbers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb14-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
</section>
<section id="nested-structs" class="level2">
<h2 class="anchored" data-anchor-id="nested-structs">Nested Structs</h2>
<p>You can also have nested structs (one within another). This is done in the same manner that you’d define any other member. For example, we can create a new struct that holds a US address</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb15-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Address</span>
<span id="cb15-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb15-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>string street<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb15-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>string city<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb15-5">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> zipcode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb15-6">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>string state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb15-7"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span></code></pre></div></div>
<p>and now we can update our <code>Student</code> struct to include the <code>Address</code> struct</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb16-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Student</span>
<span id="cb16-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb16-3">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb16-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>string name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb16-5">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float</span> gpa<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb16-6">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> gradeLevel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb16-7">    Address address</span>
<span id="cb16-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span></code></pre></div></div>
<p>To access member struct, we use the dot notation twice</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb17-1">Student student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb17-2">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>street <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"123 Fake St."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb17-3">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>city <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Springfield"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb17-4">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>zipcode <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">97475</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb17-5">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>state <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OR"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Or, if we’re using a pointer to a struct we use the arrow and dot operators together</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb18-1">Student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-2">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>street <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"123 Fake St."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-3">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>city <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Springfield"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-4">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>zipcode <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">97475</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-5">student<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>address<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>state <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OR"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>We’ve learned what a struct is, what it’s used for, and different ways of using structs. Now, go on and make use of this knowledge to create some great programs!</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references"><a name="references"></a>References</h2>
<ol type="1">
<li><a href="https://www.pearson.com/us/higher-education/product/Gaddis-Starting-Out-with-C-from-Control-Structures-to-Objects-8th-Edition/9780133769395.html">Starting out with C++: From Control Structure Through Objects, 8th Edition</a></li>
<li><a href="https://www.cprogramming.com/tutorial/lesson7.html">Structures in C++ - Tutorial - Cprogramming.com</a></li>
</ol>


</section>

 ]]></description>
  <category>c++</category>
  <category>struct</category>
  <category>beginner</category>
  <category>data structure</category>
  <guid>https://lab137.org/articles/c-simple-structs-usage/</guid>
  <pubDate>Wed, 19 Jun 2019 19:00:00 GMT</pubDate>
</item>
<item>
  <title>Building a Linked Stack: Part 3</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/building-a-linked-stack-part-3/</link>
  <description><![CDATA[ 




<p><em>This is the third article in a multi-part series on the <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">stack data structure</a>. This series defines what a stack is and what it does, then implements a link-based stack</em></p>
<p><a href="../../articles/building-a-linked-stack-part-2">Earlier</a>, we learned about nodes and the top node and we also implemented the <code>is_empty</code> and <code>push</code> methods. In the next article we’ll finish implementing our <code>LinkedStack</code> class by implementing the pop and peek methods.</p>
<section id="what-we-have-so-far" class="level2">
<h2 class="anchored" data-anchor-id="what-we-have-so-far">What We Have So Far</h2>
<p>So far, we’ve implemented the <code>is_empty</code> and <code>push</code> methods. Before we get going it’s a good idea to take a step back and see the big picture. Let’s take a look at what we have at the moment</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> LinkedStack(StackInterface):</span>
<span id="cb1-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Defines a link-based stack"""</span></span>
<span id="cb1-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb1-5"></span>
<span id="cb1-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_empty(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-7">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Determines if the stack is empty"""</span></span>
<span id="cb1-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb1-9"></span>
<span id="cb1-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb1-11">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds a new entry to the top of the stack"""</span></span>
<span id="cb1-12">        node <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Node(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>entry)</span>
<span id="cb1-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty():</span>
<span id="cb1-14">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb1-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb1-16">            node.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top</span>
<span id="cb1-17">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb1-18"></span>
<span id="cb1-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span></code></pre></div></div>
<section id="the-pop-method" class="level3">
<h3 class="anchored" data-anchor-id="the-pop-method">The Pop Method</h3>
<p>Now, we’re going to implement the <code>pop</code> method. The specifications from <a href="../../articles/building-a-linked-stack-part-1">the first article</a> show that we need to obey the following behavior</p>
<ol type="1">
<li><code>(new Stack()).pop() = False</code></li>
<li><code>(a_stack.push(item)).pop() = True</code></li>
</ol>
<p>This means that if we try to pop an item off of a stack, then <code>pop</code> should return <code>False</code> if the stack is empty and <code>True</code> otherwise. Pretty straightforward.</p>
<p>To get this behavior, we should first check if the stack is empty and immediately return <code>False</code> if it is.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb2-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the top of the stack"""</span></span>
<span id="cb2-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty():</span>
<span id="cb2-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span></code></pre></div></div>
<p>If the stack <em>isn’t</em> empty, then we need to remove the first item. A way that we can do that is to advance the reference to the top node and then return <code>True</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb3-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span></code></pre></div></div>
<p>Putting this together results in</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb4-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the top of the stack"""</span></span>
<span id="cb4-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty():</span>
<span id="cb4-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb4-5"></span>
<span id="cb4-6">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb4-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span></code></pre></div></div>
<p>Personally, I’m ok with having more than one <code>return</code> in a function. However, I’m a firm believer in making sure that one’s code tells an easy-to-follow story (just think of the person that has to read your code next is a homicidal maniac who is triggered by unclear code) and I think that we can tell the <code>pop</code> story a little better.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb5-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the top of the stack"""</span></span>
<span id="cb5-3">    can_pop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty()</span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> can_pop:</span>
<span id="cb5-5">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Advance the top of the stack to the next node</span></span>
<span id="cb5-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb5-7"></span>
<span id="cb5-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> can_pop</span></code></pre></div></div>
<p>I believe that the above will give me a slightly longer life.</p>
</section>
<section id="the-peek-method" class="level3">
<h3 class="anchored" data-anchor-id="the-peek-method">The Peek Method</h3>
<p>Now, we’re going to implement the <code>peek</code> method. The specifications from <a href="../../articles/building-a-linked-stack-part-1">the first article</a> show that we need to obey the following behavior</p>
<ol type="1">
<li><code>(new Stack()).peek() = error</code></li>
<li><code>(a_stack.push(item)).peek() = item</code></li>
</ol>
<p>This means that if we try to peek at an item of a stack, then <code>peek</code> should raise an error if the stack is empty and return the item (without modifying the stack!) otherwise. Pretty straightforward, but it will require us to create our own exception.</p>
<p>The <a href="https://docs.python.org/3/library/exceptions.html#Exception">documentation</a> states that when creating user-defined exceptions we should derive from the <code>Exception</code> class, so that’s what we’re going to do. We’re going to go with a meaningful name, otherwise we may not live very long.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># exception.py</span></span>
<span id="cb6-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EmptyException(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>):</span>
<span id="cb6-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Exception that's raised when a data structure is empty"""</span></span></code></pre></div></div>
<p>That’s it! Notice how we didn’t have to import any modules. Now, let’s start working on <code>peek</code>. Just like <code>pop</code>, we need to see if the stack is empty, and if it is, raise an <code>EmptyException</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> peek(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb7-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Returns the top of the stack"""</span></span>
<span id="cb7-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb7-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> EmptyException(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Stack is empty"</span>)</span>
<span id="cb7-5"></span>
<span id="cb7-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.data</span></code></pre></div></div>
<p>Notice how we’re returning the item with <code>self.top.data</code> instead of using <code>self.top</code>. The first bit returns the item while the second returns the node, which is <em>not</em> what we want to do.</p>
</section>
<section id="some-python-bits" class="level3">
<h3 class="anchored" data-anchor-id="some-python-bits">Some Python Bits</h3>
<p>Since we’re using Python, there’s something that we can do to make <em>using</em> our code a little easier. We can implement the <a href="https://docs.python.org/3.7/reference/datamodel.html#object.__repr__"><code>__repr__</code> dunder method</a>. which will</p>
<blockquote class="blockquote">
<p>compute the “official” string representation of an object.</p>
</blockquote>
<p>This is nice to have when using the <abbr title="Read-Eval-Print Loop">REPL</abbr>, which we’ll be using later.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb8-2">    nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb8-3">    curr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top</span>
<span id="cb8-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> curr:</span>
<span id="cb8-5">        nodes.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(curr))</span>
<span id="cb8-6">        curr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> curr.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb8-7"></span>
<span id="cb8-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'['</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', '</span>.join(nodes) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">']'</span></span></code></pre></div></div>
</section>
<section id="putting-it-all-together" class="level3">
<h3 class="anchored" data-anchor-id="putting-it-all-together">Putting it All Together</h3>
<p>Our complete implementation of the linked stack is as follows</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># interface.py</span></span>
<span id="cb9-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> abc</span>
<span id="cb9-3"></span>
<span id="cb9-4"></span>
<span id="cb9-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> StackInterface(abc.ABC):</span>
<span id="cb9-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""An abstract base class that defines a stack"""</span></span>
<span id="cb9-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb9-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_empty(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-9">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Determines if the stack is empty"""</span></span>
<span id="cb9-10"></span>
<span id="cb9-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb9-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> peek(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-13">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Returns the top of the stack"""</span></span>
<span id="cb9-14"></span>
<span id="cb9-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb9-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-17">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the top of the stack"""</span></span>
<span id="cb9-18"></span>
<span id="cb9-19">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb9-20">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb9-21">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds data to the top of the stack"""</span></span>
<span id="cb9-22"></span>
<span id="cb9-23">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb9-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb9-25">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds a new entry to the top of the stack"""</span></span>
<span id="cb9-26"></span>
<span id="cb9-27"></span>
<span id="cb9-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># stack.py</span></span>
<span id="cb9-29"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> exception <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> EmptyException</span>
<span id="cb9-30"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> interface <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StackInterface</span>
<span id="cb9-31"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> node <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Node</span>
<span id="cb9-32"></span>
<span id="cb9-33"></span>
<span id="cb9-34"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> LinkedStack(StackInterface):</span>
<span id="cb9-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Defines a link-based stack"""</span></span>
<span id="cb9-36">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-37">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb9-38"></span>
<span id="cb9-39">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_empty(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-40">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Determines if the stack is empty"""</span></span>
<span id="cb9-41">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb9-42"></span>
<span id="cb9-43">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> peek(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-44">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Returns the top of the stack"""</span></span>
<span id="cb9-45">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty():</span>
<span id="cb9-46">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> EmptyException(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Stack is empty"</span>)</span>
<span id="cb9-47"></span>
<span id="cb9-48">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.data</span>
<span id="cb9-49"></span>
<span id="cb9-50">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-51">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the top of the stack"""</span></span>
<span id="cb9-52">        can_pop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty()</span>
<span id="cb9-53">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> can_pop:</span>
<span id="cb9-54">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Advance the top of the stack to the next node</span></span>
<span id="cb9-55">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb9-56"></span>
<span id="cb9-57">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> can_pop</span>
<span id="cb9-58"></span>
<span id="cb9-59">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb9-60">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds a new entry to the top of the stack"""</span></span>
<span id="cb9-61">        node <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Node(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>entry)</span>
<span id="cb9-62">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top:</span>
<span id="cb9-63">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb9-64">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb9-65">            node.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top</span>
<span id="cb9-66">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb9-67"></span>
<span id="cb9-68">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb9-69"></span>
<span id="cb9-70">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-71">        nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb9-72">        curr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top</span>
<span id="cb9-73">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> curr:</span>
<span id="cb9-74">            nodes.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(curr))</span>
<span id="cb9-75">            curr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> curr.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb9-76"></span>
<span id="cb9-77">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'['</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', '</span>.join(nodes) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">']'</span></span>
<span id="cb9-78"></span>
<span id="cb9-79"></span>
<span id="cb9-80"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># node.py</span></span>
<span id="cb9-81"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Node:</span>
<span id="cb9-82">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""A node in a chain"""</span></span>
<span id="cb9-83"></span>
<span id="cb9-84">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb9-85">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb9-86">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data</span>
<span id="cb9-87"></span>
<span id="cb9-88">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-89">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.data)</span>
<span id="cb9-90"></span>
<span id="cb9-91"></span>
<span id="cb9-92"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># exception.py</span></span>
<span id="cb9-93"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EmptyException(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>):</span>
<span id="cb9-94">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Exception that's raised when a data structure is empty"""</span></span></code></pre></div></div>
</section>
</section>
<section id="using-the-stack" class="level2">
<h2 class="anchored" data-anchor-id="using-the-stack">Using the Stack</h2>
<p>Let’s play around with the stack a little using the REPL (I prefer IPython). We can make sure we’ve met our specifications. As a recap, here they are</p>
<ol type="1">
<li><code>(new Stack()).isEmpty() = True</code></li>
<li><code>(new Stack()).pop() = False</code></li>
<li><code>(new Stack()).peek() = error</code></li>
<li><code>(a_stack.push(item)).isEmpty() = False</code></li>
<li><code>(a_stack.push(item)).peek() = item</code></li>
<li><code>(a_stack.push(item)).pop() = True</code></li>
</ol>
<p>So, now let’s fire up that REPL and test out our shiny stack.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]: stack <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LinkedStack()</span>
<span id="cb10-2"></span>
<span id="cb10-3">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]: stack.is_empty()</span>
<span id="cb10-4">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb10-5"></span>
<span id="cb10-6">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]: stack.pop()</span>
<span id="cb10-7">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb10-8"></span>
<span id="cb10-9">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]: stack.peek()</span>
<span id="cb10-10"></span>
<span id="cb10-11"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---------------------------------------------------------------------------</span></span>
<span id="cb10-12">EmptyException                            Traceback (most recent call last)</span>
<span id="cb10-13"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>ipython<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e84</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">c3c721a3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>module<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">----&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> stack.peek()</span>
<span id="cb10-15"></span>
<span id="cb10-16"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>ipython<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">a54ea098db0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> peek(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>)</span>
<span id="cb10-17">     <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>         <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""Returns the top of the stack"""</span></span>
<span id="cb10-18">     <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>         <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empt():</span>
<span id="cb10-19"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>             <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> EmptyException(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Stack is empty"</span>)</span>
<span id="cb10-20">     <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span></span>
<span id="cb10-21">     <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>         <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top.data</span>
<span id="cb10-22"></span>
<span id="cb10-23">EmptyException: Stack <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> empty</span>
<span id="cb10-24"></span>
<span id="cb10-25">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]: stack.pop()</span>
<span id="cb10-26">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb10-27"></span>
<span id="cb10-28">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]: stack.push(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb10-29">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb10-30"></span>
<span id="cb10-31">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]: stack.is_empty()</span>
<span id="cb10-32">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb10-33"></span>
<span id="cb10-34">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]: stack.push(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb10-35">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb10-36"></span>
<span id="cb10-37">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]: stack.peek()</span>
<span id="cb10-38">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb10-39"></span>
<span id="cb10-40">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>]: stack.pop()</span>
<span id="cb10-41">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>]: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb10-42"></span>
<span id="cb10-43">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>]: stack.peek()</span>
<span id="cb10-44">Out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span></code></pre></div></div>
<p>We can see that our stack implements the specifications and works quite nicely. Although this may not be the best (e.g., most efficient) implementation, it does implement the specifications and in a manner that is clear and tells a nice story (i.e., we won’t get killed with this code, hopefully).</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this article, we learned about nodes and the top node and we also implemented the <code>is_empty</code> and <code>push</code> methods. In the next article we’ll finish implementing our <code>LinkedStack</code> class by implementing the pop and peek methods.</p>


</section>

 ]]></description>
  <category>data structure</category>
  <category>stack</category>
  <category>python</category>
  <guid>https://lab137.org/articles/building-a-linked-stack-part-3/</guid>
  <pubDate>Wed, 12 Jun 2019 19:02:00 GMT</pubDate>
</item>
<item>
  <title>Building a Linked Stack: Part 2</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/building-a-linked-stack-part-2/</link>
  <description><![CDATA[ 




<p><em>This is the second article in a multi-part series on the <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">stack data structure</a>. This series defines what a stack is and what it does, then implements a link-based stack</em></p>
<p><a href="../../articles/building-a-linked-stack-part-3">Earlier</a>, we talked about what a stack is, what a linked stack is, and then we wrote an interface for a stack. In this article, we’ll start implementing a <em>singly</em>-linked stack starting with implementing a node and then implementing the <code>is_empty</code> and <code>push</code> methods using the stack interface that we made.</p>
<section id="a-singly-linked-stack" class="level2">
<h2 class="anchored" data-anchor-id="a-singly-linked-stack">A Singly-Linked Stack</h2>
<p>Recall that a stack is a data structure that holds data in <abbr title="Last In First Out">LIFO</abbr> order. When new data is added to the stack it is added to the top and when data is removed it is removed from the top. We can also check how many entries are in the stack, check if it’s empty, and get a copy of the top entry too. This is, abstractly, what a stack is. But, what is a <em>singly</em>-linked stack?</p>
<p>A singly-linked stack holds its data as chain of nodes. Each node in the chain holds the data and a reference to the next node in the chain such as shown in the figure below (recycled from the previous post). We need this reference to the next node because it can be anywhere in memory.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/singly-linked-list.svg" class="img-fluid figure-img"></p>
<figcaption>A link of nodes</figcaption>
</figure>
</div>
<section id="using-the-stack-interface" class="level3">
<h3 class="anchored" data-anchor-id="using-the-stack-interface">Using the Stack Interface</h3>
<p>In the previous article we created an interface for a stack. Now is the time to use it. The way that we’re going to use it is by making our <code>LinkedStack</code> class a sublcass of the <code>StackInterface</code> class. By subclassing the <code>StackInterface</code> class, we are forced to live up to the specs that we laid out earlier.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> LinkedStack(StackInterface):</span>
<span id="cb1-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Defines a link-based stack"""</span></span></code></pre></div></div>
<p>And that’s it! Now we just have to override the methods declared as abstract methods in the <code>StackInterface</code> class.</p>
</section>
<section id="a-node" class="level3">
<h3 class="anchored" data-anchor-id="a-node">A Node</h3>
<p>Previously, we learned that a node is something that holds data and a reference to the next node. Now, let’s see how we can define a node. If you’re using Python 3.7+, then you can use the <code>dataclasses</code> module, otherwise, we’re going to define a node using a vanilla Python class.</p>
<p>Since a node holds <em>data</em> and a reference to the <em>next</em> node, our node class will have <code>data</code> and <code>next</code> attributes and we’ll implement a dunder method to make our lives easier.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># node.py</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Node:</span>
<span id="cb2-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""A node in a chain"""</span></span>
<span id="cb2-4"></span>
<span id="cb2-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb2-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span></span>
<span id="cb2-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data</span>
<span id="cb2-8"></span>
<span id="cb2-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb2-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.data)</span></code></pre></div></div>
<p>The default values of the attributes inherently make sense. If we instantiate a <code>node</code> object without specifying any data or the next node, then those should be <code>None</code>. Next, we’ll start connecting multiple nodes together to make the underlying chain for our linked stack.</p>
</section>
<section id="the-top-node" class="level3">
<h3 class="anchored" data-anchor-id="the-top-node">The Top Node</h3>
<p>Recall that the chain underlying the linked stack is made up of a series of nodes, each one pointing to the next. Every chain has a starting point, and in the linked stack that starting point is called the top node. It serves as a way to find the other nodes in the stack.</p>
<p>The top node has two possible states:</p>
<ol type="1">
<li>Empty (<code>None</code> is how this will be expressed)</li>
<li>Occupied and will hold a node</li>
</ol>
<p>When we instantiate the linked stack it will be empty so the top node will be <code>None</code>. When an entry is pushed onto the stack it gets added to the front and, therefore, the top will hold the most recently added entry.</p>
<p>When an entry is popped from the stack the that entry comes from the top which is the top node. As you can see, most of the action is happening at the top of the chain.</p>
<p>Our <code>__init__</code> method ends up being</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb3-2">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span></code></pre></div></div>
</section>
<section id="the-is_empty-method" class="level3">
<h3 class="anchored" data-anchor-id="the-is_empty-method">The is_empty Method</h3>
<p>According to our specifications laid out in the previous post, we need to implement a method that determines if the stack is empty or not. An easy way to do that is to check if the top node is <code>None</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_empty(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb4-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Determines if the stack is empty"""</span></span>
<span id="cb4-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span></code></pre></div></div>
</section>
<section id="the-push-method" class="level3">
<h3 class="anchored" data-anchor-id="the-push-method">The Push Method</h3>
<p>We just found out that the <code>push</code> method puts the data at the start of the chain. How can we implement this? It’s actually pretty straightforward, but we do have to stick to the specification which says that we must accept an entry parameter and return <code>True</code> if the entry was successfully added and return <code>False</code> otherwise. Here’s a pseudocode version of what we’re going to do</p>
<ol type="1">
<li>Create a new node that we’re going to add to the stack (we’ll call this <code>node</code>)</li>
<li>Check if the stack is empty
<ol type="1">
<li>If the stack is empty, set the top node to be the node that we just created</li>
<li>Otherwise, set <code>node.next</code> to the top node</li>
</ol></li>
<li>Increase the number of items in the stack</li>
<li>Return <code>True</code></li>
</ol>
<p>Here’s the Python code</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb5-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds a new entry to the top of the stack"""</span></span>
<span id="cb5-3">    node <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Node(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>entry)</span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_empty():</span>
<span id="cb5-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb5-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb5-7">        node.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top</span>
<span id="cb5-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> node</span>
<span id="cb5-9"></span>
<span id="cb5-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span></code></pre></div></div>
</section>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this article, we learned about nodes and the top node and we also implemented the <code>is_empty</code> and <code>push</code> methods. In the next article we’ll finish implementing our <code>LinkedStack</code> class by implementing the pop and peek methods.</p>
</section>
<section id="resources" class="level2">
<h2 class="anchored" data-anchor-id="resources">Resources</h2>
<ol type="1">
<li>A link of nodes. Image courtesy of <a href="https://commons.wikimedia.org/wiki/File:Singly-linked-list.svg">Lasindi</a></li>
</ol>


</section>

 ]]></description>
  <category>data structure</category>
  <category>stack</category>
  <category>python</category>
  <guid>https://lab137.org/articles/building-a-linked-stack-part-2/</guid>
  <pubDate>Wed, 12 Jun 2019 19:01:00 GMT</pubDate>
</item>
<item>
  <title>Building a Linked Stack: Part 1</title>
  <dc:creator>Jay Ess</dc:creator>
  <link>https://lab137.org/articles/building-a-linked-stack-part-1/</link>
  <description><![CDATA[ 




<p><em>This is the first article in a multi-part series on the <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">stack data structure</a>. This series defines what a stack is and what it does, then implement a link-based stack</em></p>
<section id="what-is-a-stack" class="level2">
<h2 class="anchored" data-anchor-id="what-is-a-stack">What is a Stack?</h2>
<p>A stack is a data structure that holds data in <abbr title="Last In First Out">LIFO</abbr> order. This means that whatever was the most recent “thing” to be put onto the stack will be the first to be removed.</p>
<p>For example, imagine that you are washing a stack of dirty dishes. As you’re washing, every time you clean one plate you pull another off the top of the stack of dirty dishes. If someone wants to give you more dishes to wash they’re going to put them on top of your stack.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/stack_of_plates.jpg" class="img-fluid figure-img"></p>
<figcaption>A stack of dirty dishes</figcaption>
</figure>
</div>
<p>That’s pretty much what the stack data structure is. It’s an ordered collection of things (with the most recently added thing at the top) and you can perform certain operations on it. You can</p>
<ul>
<li>see if the stack is empty</li>
<li>see how many things are in it</li>
<li>take an item off of the top (pop!)</li>
<li>add something to the top (push!)</li>
<li>see what the item at the top is (peek!)</li>
</ul>
<p>We can reword the above list into pseudocode that will make our lives easier when we start writing some code (it’s usually a good idea to put your ideas into pseudocode before writing actual code).</p>
<ol type="1">
<li><code>(new Stack()).isEmpty() = True</code></li>
<li><code>(new Stack()).pop() = False</code></li>
<li><code>(new Stack()).peek() = error</code></li>
<li><code>(a_stack.push(item)).isEmpty() = False</code></li>
<li><code>(a_stack.push(item)).peek() = item</code></li>
<li><code>(a_stack.push(item)).pop() = True</code></li>
</ol>
<p>In order, this is what they mean</p>
<ol type="1">
<li>A new stack should be empty</li>
<li>You can’t take something off the top of an empty stack</li>
<li>Trying to see what’s at the top of an empty stack results in an error</li>
<li>A stack with something in it isn’t empty</li>
<li>Looking (peeking) at the top gives you the thing that was most recently added</li>
<li>You can remove something from a non-empty stack</li>
</ol>
<p>This may sound somewhat similar to an array. It is, and a stack can be implemented using an array. But, elements in an array can be accessed at will while elements in a stack are accessed in LIFO order.</p>
<section id="some-applications-of-stacks" class="level3">
<h3 class="anchored" data-anchor-id="some-applications-of-stacks">Some Applications of Stacks</h3>
<p>But, what’s the point? Why would we want to have a data structure that remembers which dish we need to wash next? Stacks are actually pretty useful and common in computing.</p>
<p>Remember, they keep track of a sequence of elements with the most recent element at the beginning of the stack. So, we can use a stack to keep track of which characters have been entered by a user, keeping track of cities visited when finding a flight path between different cities (backtracking), and computers use them to hold local variables and return addresses for function calls (stack frame).</p>
</section>
<section id="implementations-of-stacks" class="level3">
<h3 class="anchored" data-anchor-id="implementations-of-stacks">Implementations of Stacks</h3>
<p>There are at least two different ways that we can make a stack: using an array (or a list in Python) or using a chain of nodes (which we’ll call a linked stack). Here, we’re going with a linked stack.</p>
</section>
</section>
<section id="the-linked-stack" class="level2">
<h2 class="anchored" data-anchor-id="the-linked-stack">The Linked Stack</h2>
<p><em>The following discussion is a general discussion about link-based data structures versus array-based data structures. For Python, the overhead of the rest of your code can be so large that the overhead of an array-based vs link-based data structures may not make much of a difference. But, this is still a useful discussion nonetheless.</em></p>
<p>Think of an array and how every element in an array is stored in contiguous blocks of memory, such as the example in the figure below. Each cell is a block of memory and the number above the cell is its address. When you want to access an element of an array you use an index such as <code>arr[4]</code> to access the fifth element of the array (assuming zero indexing). This is actually an offset from the address of the first element in the array. This gives us quick and direct access to the data. This quick and direct access comes at a cost.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/array.svg" class="img-fluid figure-img"></p>
<figcaption>A block of memory representing an array</figcaption>
</figure>
</div>
<p>When an array has data added to it and it is, extra memory must be allocated to make room for the data (and then some) and the data must be copied to the new memory location. This is one of the costs of using an array, the time that it takes to allocate more space for the array and copying its data to the newly allocated space. We could preallocate more room for the data ahead of time, but that would be potentially wasted space (this is actually what Python does with lists) and increases the complexity of the data structure.</p>
<p>What about <em>removing</em> data? If we need to remove data at the end of the array then we’re fine. But, removing data anywhere else requires us to either remember which elements have been removed (to guard against stale data), or to readjust all the following elements.</p>
<p>If we’re going to mostly be reading and updating data, or if we know how much space our stack will need then an array is a good choice to use as the data store for a stack. Otherwise, if we’re going to be doing a lot of adding and removing data then we should look into using a linked stack.</p>
<p>A linked stack is made of a <a href="https://en.wikipedia.org/wiki/Linked_data_structure">set of nodes that are linked together</a> by references, a.k.a the link. Depending on the language, this reference can be a pointer variable (like in C++) or a variable that holds a reference to the next node in the chain (what we’re going to do with Python). (The point is that instead of using contiguous memory addresses a linked stack (or linked data structures in general) use memory from wherever the system allocates space for you. This means that, for the most part, linked stacks can be as large as you need them to be.)</p>
<p>So, a node is an object (<strong>don’t</strong> think of the CS idea of an object just yet!) that holds data and a reference to another node. If there is no other node, then that reference is <code>None</code> in Python (or, <code>nullptr</code> in C++). In the figure below, the left side of the node is the data and the right side is a reference to the next node indicated by an arrow.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/node_scoured.svg" class="img-fluid figure-img"></p>
<figcaption>A single node</figcaption>
</figure>
</div>
<p>A chain of nodes is shown in the figure below. The head consists of a head node and the nodes following it. The end of the chain is the block all the way to the right with an “X” in it. This “X” represents a reference to <code>None</code> in Python (or <code>nullptr</code> in C++) indicating the end of the chain.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://lab137.org/articles/img/stack_of_plates.jpg" class="img-fluid figure-img"></p>
<figcaption>A stack of dirty dishes</figcaption>
</figure>
</div>
<p>Now, linked data structures aren’t perfect and there will be some tradeoffs to using one versus using an array. First, they take more memory because they must contain a reference to the next node in each node in the chain. Second, they do not support <a href="https://en.wikipedia.org/wiki/Random_access">random access</a>. You must start with the head of the structure and traverse the chain until you reach the desired entry.</p>
</section>
<section id="the-stack-interface" class="level2">
<h2 class="anchored" data-anchor-id="the-stack-interface">The Stack Interface</h2>
<p>We’re going to start with defining an interface for the stack then move on to implementing the linked stack in the <a href="../../articles/building-a-linked-stack-part-2">next article</a>. The point of making an interface is to make sure that we implement the correct methods in our implementation. Now, this may not seem like it’s such a big deal right now (after all, we’re only implementing on type of stack, right?), but if we wanted to make a different type of stack then we can inherit from this interface and code to the specifications that are laid out in it (see <a href="https://softwareengineering.stackexchange.com/a/108681">these</a> <a href="https://softwareengineering.stackexchange.com/a/108267">answers on SE</a>).</p>
<p>Anyways, we’re going to use Python’s <code>abc</code> module to create an <em>interface</em> that we’ll use later on in our linked stack <em>implementation</em>. By using the <a href="https://docs.python.org/3/library/abc.html#abc.ABC"><code>abc.ABC</code> class</a> and the <a href="https://docs.python.org/3/library/abc.html#abc.abstractmethod"><code>abc.abstractmethod</code> decorator</a>, we can insure that who ever uses our interface implements it to the specifications by implementing the methods that use the <code>abc.abstractmethod</code> decorator. If they’re not implemented, then a <code>TypeError</code> will be raised when the class is attempted to be instantiated. You can get the code from a <a href="https://gist.github.com/jay3ss/5641fa3de11129118dc2fae305135ba8">gist on GitHub</a>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># interfaces.py</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> abc</span>
<span id="cb1-3"></span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> StackInterface(abc.ABC):</span>
<span id="cb1-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""An abstract base class that defines a stack"""</span></span>
<span id="cb1-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb1-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_empty(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-9">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Determines if the stack is empty</span></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :return True if the stack is empty, False otherwise</span></span>
<span id="cb1-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb1-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb1-13"></span>
<span id="cb1-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb1-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> peek(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-16">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Returns the top of the stack</span></span>
<span id="cb1-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :pre The stack isn't empty</span></span>
<span id="cb1-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :return The entry at the top of the stack</span></span>
<span id="cb1-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb1-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb1-21"></span>
<span id="cb1-22">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb1-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-24">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Removes the entry from the top of the stack</span></span>
<span id="cb1-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :post The entry at the top of the stack will be removed, if possible</span></span>
<span id="cb1-26"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :return True if removal was successful, False otherwise</span></span>
<span id="cb1-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb1-28">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb1-29"></span>
<span id="cb1-30">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abc.abstractmethod</span></span>
<span id="cb1-31">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entry):</span>
<span id="cb1-32">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Adds an entry to the top of the stack</span></span>
<span id="cb1-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :post The entry will be added to the top of the stack, if possible</span></span>
<span id="cb1-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        :return True if addition was successful, False otherwise</span></span>
<span id="cb1-35"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb1-36">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span></code></pre></div></div>
<p>An abstract base class (which is what the interface here is) cannot be instantiated, hence the word <em>abstract</em>. Go ahead and try, I did. The result was</p>
<pre><code>TypeError: Can't instantiate abstract class StackInterface with abstract methods is_empty, peek, pop, push</code></pre>
<p>This is good because we’ve described a stack as a data structure that has these methods. Any class that subclasses the <code>StackInterface</code> class <strong>must</strong> implement these methods and therefore live up to the specification that we wrote. If these methods haven’t been implemented, then the specifications have not been met and the subclass can’t be instantiated. Neat!</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this article we talked about what a stack is, what a linked stack is, and then we wrote an interface for a stack. In the <a href="../articles/building_a_linked_stack_part_2.html">next article</a>, we’ll start implementing the linked stack by implementing the <code>push</code> method.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ol type="1">
<li><a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">Stack (Abstract Data Type)</a></li>
<li><a href="https://docs.python.org/3/faq/design.html#how-are-lists-implemented-in-cpython">How Are Lists Implemented in CPython?</a></li>
<li><a href="https://en.wikipedia.org/wiki/Linked_data_structure">Linked Data Structure</a></li>
<li><a href="https://www.pearson.com/us/higher-education/product/Carrano-Data-Abstraction-Problem-Solving-with-C-Walls-and-Mirrors-6th-Edition/9780132923729.html">Data Abstraction &amp; Problem Solving with C++: Walls and Mirrors, 6th Edition</a></li>
<li><a href="https://www.pearson.com/us/higher-education/product/Gaddis-Starting-Out-with-C-from-Control-Structures-to-Objects-8th-Edition/9780133769395.html">Starting out with C++: From Control Structure Through Objects, 8th Edition</a></li>
<li><a href="https://pymotw.com/3/abc/">PyMOTW 3: abc — Abstract Base Classes</a></li>
<li><a href="http://blog.robertelder.org/interfaces-most-important-software-engineering-concept/">Interfaces - The Most Important Software Engineering Concept</a></li>
</ol>
</section>
<section id="resources" class="level2">
<h2 class="anchored" data-anchor-id="resources">Resources</h2>
<ol type="1">
<li>Stack of dirty dishes. Image courtesy of <a href="https://torange.biz">torange.biz</a>, <a href="https://creativecommons.org/licenses/by/4.0/">License CC-BY 4.0</a></li>
<li>A block of memory representing an array. Image courtesy of <a href="https://commons.wikimedia.org/wiki/User:Jarkko_Piiroinen">Jarkko Piiroinen</a></li>
</ol>


</section>

 ]]></description>
  <category>data structure</category>
  <category>stack</category>
  <category>python</category>
  <guid>https://lab137.org/articles/building-a-linked-stack-part-1/</guid>
  <pubDate>Wed, 12 Jun 2019 19:00:00 GMT</pubDate>
</item>
</channel>
</rss>
