{"id":2336,"date":"2018-08-12T02:35:04","date_gmt":"2018-08-12T07:35:04","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=2336"},"modified":"2020-01-08T10:01:53","modified_gmt":"2020-01-08T15:01:53","slug":"python-how-to-implement-a-lifo-stack","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2018\/08\/12\/python-how-to-implement-a-lifo-stack\/","title":{"rendered":"Python: How to implement a LIFO stack"},"content":{"rendered":"<p>Stacks are a computer science data structure useful for special types of computation where you essentially add information to the top of the &#8216;stack&#8217; and also remove information only from the top of the stack. LIFO stands for Last-In-First-Out, which is an acronym that aids in remembering what is going on in a stack, i.e. the last item added to the to the stack is the first item that will be removed from the stack.<\/p>\n<p>In Python, a stack can be implemented as an array where we use built-in Python methods such as <code>list.append()<\/code> which can &#8216;push&#8217; information onto the stack and <code>list.pop()<\/code> which can &#8216;pop&#8217; information off of the stack.<\/p>\n<p>Both of these methods act on the <em>end<\/em> of an array, so all we have to do to visualize a Python list as a stack is turn the array 90 degrees counter clockwise so that the\u00a0 front of the array is at the bottom and the end of the array is considered the &#8216;top&#8217; of the stack. Or, you can just imagine the horizontal end of a Python list as the top of the stack.<\/p>\n<p>Here is what Wikipedia says about stacks:<\/p>\n<blockquote><p>In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations:<\/p>\n<p>push, which adds an element to the collection, and<br \/>\npop, which removes the most recently added element that was not yet removed.<\/p><\/blockquote>\n<p>Here is one way to visualize what is going on in a stack:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2338\" src=\"http:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack.jpg\" alt=\"\" width=\"473\" height=\"257\" srcset=\"https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack.jpg 473w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-300x163.jpg 300w\" sizes=\"auto, (max-width: 473px) 100vw, 473px\" \/><\/p>\n<p>Next I will illustrate how a stack can be useful in solving real problems. Let&#8217;s say I am creating a parser that reads every line of a source code file looking for opening and closing parenthesis in order to capture all function calls. The parser is working except it is finding function calls that should not be included because they are inside of larger strings such as HTML constructions or SQL queries. For example, here is an HTML construction that contains function calls that should be ignored due to the fact that the calls are inside of a string.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\">html += '&lt;p&gt;&lt;a href=\"#\" onclick=\"javascript:$(\\'#help_note\\').hide();\"&gt;Close&lt;\/a&gt;&lt;\/p&gt;';<\/pre>\n<p>Technically there are function calls inside this string, but I don&#8217;t want to capture them because I am trying to gather only function calls that are actually being used in the surrounding code. Notice this string is surrounded by single quotes, then it has some double quotes inside, followed by more double quotes with single quotes inside them.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2341\" src=\"http:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes.png\" alt=\"\" width=\"1220\" height=\"38\" srcset=\"https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes.png 1220w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes-300x9.png 300w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes-768x24.png 768w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes-1024x32.png 1024w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/single-double-quotes-676x21.png 676w\" sizes=\"auto, (max-width: 1220px) 100vw, 1220px\" \/><\/p>\n<p>The problem is, how do you parse this line so that you can tell where the string begins and ends? You can&#8217;t just go to the next occurrence of single quote that you find, because it is inside of another double quote inside the string. Counting single and double quotes like you would count opening and closing brackets won&#8217;t work either, because you don&#8217;t know ahead of time how long the string is so you don&#8217;t know if any given quotes you find are the last.<\/p>\n<p>This is where the concept of a stack becomes really useful. When reading a line of text like the above example, character by character from left to right, whenever we encounter a single or double quote, we can add it to the stack. Because we have both single and double quotes, we need to represent them differently in the stack. For example, we could call the single quotes &#8216;s&#8217; and the double quotes &#8216;d&#8217;.<\/p>\n<h5><strong>The algorithm works like this:<\/strong><\/h5>\n<p>If we see a single quote, push an &#8216;s&#8217; onto the stack. If we see a double quote, push a &#8216;d&#8217; onto the stack. However, before adding an &#8216;s&#8217; or &#8216;d&#8217; to the stack, check the top of the stack to see if it matches what we just found. For example, if I just found double quotes, check the top of the stack. If the top of the stack already contains a &#8216;d&#8217;, then pop the &#8216;d&#8217; off of the stack. Otherwise, push a &#8216;d&#8217; onto the stack.<\/p>\n<p>This works the same way for &#8216;s&#8217;. When\u00a0 encountering a new single quote in the string, if the top of the stack already contains an &#8216;s&#8217;, then pop it off of the stack. Otherwise, push an &#8216;s&#8217; onto the stack.<\/p>\n<p>Now all we have to do to find the end of the string is to check the stack to see if it is empty. If the stack is empty, we have found the end of the string and we are done.<\/p>\n<p>Here is how this plays out with the example string above:<\/p>\n<ul>\n<li>Encountered a single quote. The top of the stack doesn&#8217;t contain an &#8216;s&#8217; already, so <strong>push<\/strong> an &#8216;s&#8217; onto the stack.<\/li>\n<li>Next we encounter a double quote. The top of the stack doesn&#8217;t contain a &#8216;d&#8217;, so <strong>push<\/strong> a &#8216;d&#8217; onto the stack.<\/li>\n<li>Next we encounter a double quote again. The top of the stack <em>does<\/em> contain a &#8216;d&#8217; already, so <strong>pop<\/strong> the &#8216;d&#8217; off of the top of the stack.<\/li>\n<li>Next we encounter a double quote. The top of the stack doesn&#8217;t contain a &#8216;d&#8217;, so <strong>push<\/strong> a &#8216;d&#8217; onto the stack.<\/li>\n<li>Next we encounter a single quote. The top of the stack doesn&#8217;t contain an &#8216;s&#8217;, so <strong>push<\/strong> an &#8216;s&#8217; onto the stack.<\/li>\n<li>Next we encounter a single quote again. The top of the stack <em>does<\/em> contain an &#8216;s&#8217;, so <strong>pop<\/strong> the &#8216;s&#8217; off of the top of the stack.<\/li>\n<li>Next we encounter a double quote again. The top of the stack <em>does<\/em> contain a &#8216;d&#8217;, so <strong>pop<\/strong> the &#8216;d&#8217; off of the top of the stack.<\/li>\n<li>Next we encounter a single quote again. The top of the stack <em>does<\/em> contain an &#8216;s&#8217;, so <strong>pop<\/strong> the &#8216;s&#8217; off of the top of the stack.<\/li>\n<li>Now the stack is empty, so we are done. We have found the end of the string.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2344\" src=\"http:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-algorithm.png\" alt=\"\" width=\"867\" height=\"271\" srcset=\"https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-algorithm.png 867w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-algorithm-300x94.png 300w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-algorithm-768x240.png 768w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/08\/stack-algorithm-676x211.png 676w\" sizes=\"auto, (max-width: 867px) 100vw, 867px\" \/><\/p>\n<p>Here is what the Python algorithm looks like:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">sq = \"'\"\ndq = '\"'\nnonQuoteLine = \"\"\nquoteStack = []\nif sq in line or dq in line:\n    for char in line:\n        if char == sq:\n\t    if len(quoteStack) == 0:\n\t\tquoteStack.append('s')\n\t    else:\n\t\tif quoteStack[-1] == 's':\n\t\t    quoteStack.pop()\n\t\telse:\n\t\t    quoteStack.append('s')\n\telif char == dq:\n\t    if len(quoteStack) == 0:\n\t\tquoteStack.append('d')\n\t    else:\n\t\tif quoteStack[-1] == 'd':\n\t\t    quoteStack.pop()\n\t\telse:\n\t\t    quoteStack.append('d')\n        if len(quoteStack) == 0:\n            nonQuoteLine += char<\/pre>\n<p>For more good information about LIFO stacks, see:<br \/>\n<a href=\"https:\/\/www.i-programmer.info\/babbages-bag\/263-stacks.html\">https:\/\/www.i-programmer.info\/babbages-bag\/263-stacks.html<\/a><\/p>\n<p>For more information about Python methods <code>append()<\/code> and <code>pop()<\/code>, see:<br \/>\n<a href=\"https:\/\/www.tutorialspoint.com\/python\/list_append.htm\">https:\/\/www.tutorialspoint.com\/python\/list_append.htm<\/a><br \/>\n<a href=\"https:\/\/docs.python.org\/3.1\/tutorial\/datastructures.html\">https:\/\/docs.python.org\/3.1\/tutorial\/datastructures.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Stacks are a computer science data structure useful for special types of computation where you essentially add information to the top of the &#8216;stack&#8217; and also remove information only from the top of the stack. LIFO stands for Last-In-First-Out, which is an acronym that aids in remembering what is going on in a stack, i.e. &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2018\/08\/12\/python-how-to-implement-a-lifo-stack\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Python: How to implement a LIFO stack<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[170,172,171,4],"class_list":["post-2336","post","type-post","status-publish","format-standard","hentry","category-python-language","tag-append","tag-lifo","tag-pop","tag-python"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2336","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=2336"}],"version-history":[{"count":11,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2336\/revisions"}],"predecessor-version":[{"id":3058,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2336\/revisions\/3058"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=2336"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=2336"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=2336"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}