<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Whiteboarding in Python</title>
    <description>The latest articles on DEV Community by Whiteboarding in Python (@pythonwb).</description>
    <link>https://dev.to/pythonwb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F467078%2Ff8dd065f-5fa1-4319-bcf2-68f26f62746f.jpeg</url>
      <title>DEV Community: Whiteboarding in Python</title>
      <link>https://dev.to/pythonwb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pythonwb"/>
    <language>en</language>
    <item>
      <title>Sum of Three, Sum of Four, and Beyond? In Python!</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Thu, 25 Mar 2021 02:20:38 +0000</pubDate>
      <link>https://dev.to/pythonwb/sum-of-three-sum-of-four-and-beyond-in-python-2224</link>
      <guid>https://dev.to/pythonwb/sum-of-three-sum-of-four-and-beyond-in-python-2224</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl"&gt;&amp;lt;&amp;lt; #21 Tree Practice&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/sum_of_k.py"&gt;View Solution on GitHub&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hUY7N0x2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://bendpetexpress.com/wp-content/uploads/2016/06/5198682308_c3cabf26ff_o.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hUY7N0x2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://bendpetexpress.com/wp-content/uploads/2016/06/5198682308_c3cabf26ff_o.jpg" alt="cat asleep on computer"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Actual pic of me after trying to solve this problem (Image: Bend Pet Express)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Today's problem has stumped many a programmer. A colleague of mine and I sat down with "Sum of Three", talked it out, and after more than an hour, finally finished a solution that was by no means elegant or optimal. I was joking with him that next we should try "Sum of Four", which I had totally made up. Turns out, &lt;a href="https://leetcode.com/problems/4sum/"&gt;it's real&lt;/a&gt;. After another long whiteboarding session, we came up with...a bunch of ideas and no solution. &lt;/p&gt;

&lt;p&gt;We were so focused on finding an elegant solution that we missed being able to solve the problem at all. But here's an obvious solution: brute force. Brute force may be simple, and it certainly isn't optimal, but it gets the job done. And when you have no other solution, it helps to have at least one way to solve it. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--05Ih0tOT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.kym-cdn.com/entries/icons/original/000/028/021/work.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--05Ih0tOT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.kym-cdn.com/entries/icons/original/000/028/021/work.jpg" alt="It ain't much, but it's honest work."&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: KnowYourMeme)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Today, we're going to look at "Sum of Three" and "Sum of Four", and solve them using brute force. Then, you'll see how we can expand the brute force solution using recursion to allow for "Sum of K", which will work for 3, 4, or any amount of numbers we want to sum up. You'll see that having a brute force solution might not be scalable, but you can still build some powerful things. &lt;/p&gt;

&lt;p&gt;Let's get started with the simpler problem, "Sum of Three". Here is the prompt: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Given an array nums of n integers and a target,
# are there elements a, b, c in nums 
# such that a + b + c = target?

# Example:

# Input: 
# nums = [-1,0,1,2,-1,-4]
# target = 0

# Output: [[-1,-1,2],[-1,0,1]]

# Notice that the solution set must not contain duplicate triplets.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Were given a list of numbers, and we want to find every three numbers in the list that sum to zero, or whichever number is specified at the target. How would you go about solving this?&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Approach
&lt;/h2&gt;

&lt;p&gt;The brute force solution will involve iteration. Imagine we look at each number, and check it against every other number, and then check those two numbers against every other other number. What does this sound like? If you said a triple nested &lt;code&gt;for&lt;/code&gt; loop, you're right (I'm sure there must also be a recursive way to do this part...let me know in the comments if you found it!). &lt;/p&gt;

&lt;p&gt;But theres one other caveat, as listed in the prompt: &lt;code&gt;Notice that the solution set must not contain duplicate triplets&lt;/code&gt;. How will we account for this? If you've been following this blog, you're probably thinking of using a set (more on this &lt;a href="https://dev.to/erikhei/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;here&lt;/a&gt;). And yep, that's what we will be using. We'll codify each working triplet into a string and put it in the set to make sure we haven't included it already. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Setup
&lt;/h2&gt;

&lt;p&gt;We're ready to start writing this bad boy. Our method &lt;code&gt;sum_of_three&lt;/code&gt; will take in two arguments: the list &lt;code&gt;nums&lt;/code&gt; and the &lt;code&gt;target&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_three(nums, target):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we need to check for an edge case. What if &lt;code&gt;nums&lt;/code&gt; has less than 3 numbers in it? Then we can't find a triplet. In this case, we'll return an empty list. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_three(nums, target):
  if len(nums) &amp;lt; 3:
    return []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we need to initialize some variables that we'll be using. Firstly, the &lt;code&gt;output&lt;/code&gt; list which will contain lists of triplets. We'll also start one of those triplet lists and call it &lt;code&gt;current&lt;/code&gt;. Once we populate &lt;code&gt;current&lt;/code&gt; with a working triplet, we can append it to &lt;code&gt;output&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  output = []
  current = []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And, as discussed earlier, we'll need to make a set. Additionally, we'll want to sort the list to make sure we don't add the same triplet to the set, just in a different order (for instance, only one of &lt;code&gt;[1, -2, 1]&lt;/code&gt; and &lt;code&gt;[1, 1, -2]&lt;/code&gt; should be added). &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  checked = set()
  nums.sort()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  3. Iteration
&lt;/h2&gt;

&lt;p&gt;We're ready to start our &lt;code&gt;for&lt;/code&gt; loops. We're making three of them, and the most important part to consider is our indices' upper and lower bounds. &lt;/p&gt;

&lt;p&gt;For the first loop, we'll start with the first number in the list and go until the 3rd from the last spot. Why? We need two additional numbers to check this with, and once we get to the 2nd or last index, there aren't enough numbers behind it to make a triplet. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for i in range(len(nums) - 2):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As a review, &lt;code&gt;range(start, end)&lt;/code&gt; accepts two arguments: a start (inclusive) and an end (exclusive). If the start argument is missing, it's assumed to be 0. &lt;/p&gt;

&lt;p&gt;Okay, what will we do inside this first &lt;code&gt;for&lt;/code&gt; loop? Here's the agenda:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add the first number to &lt;code&gt;current&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Subtract that number from the sum. &lt;/li&gt;
&lt;li&gt;Check it with the other numbers.&lt;/li&gt;
&lt;li&gt;Undo steps 1 and 2 so we can move on to the next number. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's write these in code. The first one is easy, simply &lt;code&gt;append&lt;/code&gt; the number at index &lt;code&gt;i&lt;/code&gt; to current. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    current.append(nums[i])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The next step is also pretty simple. You can subtract from the &lt;code&gt;target&lt;/code&gt;, but I prefer making a new variable that makes it clear that we're changing it, called &lt;code&gt;working_target&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    working_target = target - nums[i]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Step 3 is more complicated. "Check it with the other numbers" is my shorthand for doing the nested &lt;code&gt;for&lt;/code&gt; loops. I'll comment it out for now.&lt;/p&gt;

&lt;p&gt;Step 4 is simple. Remove the last element from current with &lt;code&gt;current.pop()&lt;/code&gt;, and to move the target back, well, we don't need to do anything because it's going to be re-instantiated each iteration. Altogether, our loop looks like this so far: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for i in range(len(nums) - 2):
    current.append(nums[i])
    working_target = target - nums[i]
    # do some for loops
    current.pop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Great, we're ready to move onto loop #2. &lt;/p&gt;

&lt;p&gt;What are our indices? We start at the index after &lt;code&gt;i&lt;/code&gt; and go until the second-to-last spot in &lt;code&gt;nums&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    for j in range(i + 1, len(nums) - 1):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we follow our steps 1-4 again. That is, we append the number at &lt;code&gt;j&lt;/code&gt; to &lt;code&gt;current&lt;/code&gt;, subtract it from &lt;code&gt;working_target&lt;/code&gt;, leave space for the next loop, and then undo steps 1 and 2. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    for j in range(i + 1, len(nums) - 1):
      working_target -= nums[j]
      current.append(nums[j])
      # do another for loop
      current.pop()
      working_target += nums[j]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we can write our innermost loop. The indices should be familiar by now, we start at &lt;code&gt;j + 1&lt;/code&gt; and go until the last index. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      for k in range(j + 1, len(nums)):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can append the number at &lt;code&gt;k&lt;/code&gt; to &lt;code&gt;current&lt;/code&gt;, but when we subtract from the &lt;code&gt;working_total&lt;/code&gt;, now we want to check if it equals zero. If the numbers all sum to the target, then &lt;code&gt;target - a - b - c = 0&lt;/code&gt; (if you remember back to algebra class). &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      for k in range(j + 1, len(nums)):
        current.append(nums[k])
        if working_target - nums[k] == 0:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What goes in the &lt;code&gt;if&lt;/code&gt; statement? Now it's time to use our set to determine if we've checked this triplet already. &lt;/p&gt;

&lt;p&gt;We can't put lists into a set, so we have to codify our triplet into a string. The following code will make a string with &amp;amp;s in between the numbers, for example, &lt;code&gt;[1, 1, -2]&lt;/code&gt; will get turned into &lt;code&gt;1&amp;amp;1&amp;amp;-2&lt;/code&gt;. You can use any character you want to deliniate the numbers, but you need something so &lt;code&gt;1, 11&lt;/code&gt; isn't confused with &lt;code&gt;11, 1&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          # make code to put in duplicate set
          code = str(current[0])
          for n in range(1, len(current)):
            code += "&amp;amp;" + str(current[n])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we can check to see if the code is in the set. If not, we can add it to the set and add &lt;code&gt;current&lt;/code&gt; to our final &lt;code&gt;output&lt;/code&gt;. Remember to add a copy of &lt;code&gt;current&lt;/code&gt;, and not just the reference. Otherwise, our triplet could change after we add it to &lt;code&gt;output&lt;/code&gt;!&lt;br&gt;&lt;br&gt;
              if code not in checked:&lt;br&gt;
                output.append(current.copy())&lt;br&gt;
                checked.add(code)&lt;/p&gt;

&lt;p&gt;Lastly, we pop the third number off of current. Altogether, the final &lt;code&gt;for&lt;/code&gt; loop:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      for k in range(j + 1, len(nums)):
        current.append(nums[k])
        if working_target - nums[k] == 0:
          # make code to put in duplicate set
          code = str(current[0])
          for n in range(1, len(current)):
            code += "&amp;amp;" + str(current[n])
          if code not in checked:
            output.append(current.copy())
            checked.add(code)
        current.pop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  4. Wrapping up Sum of Three
&lt;/h2&gt;

&lt;p&gt;All that's left is to return our &lt;code&gt;output&lt;/code&gt; list. Then, we're done! Here is the full method; be sure that your indentation matches exactly after all those &lt;code&gt;for&lt;/code&gt; loops: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_three(nums, target):
  if len(nums) &amp;lt; 3:
    return []
  output = []
  current = []
  checked = set()
  nums.sort()
  for i in range(len(nums) - 2):
    current.append(nums[i])
    working_target = target - nums[i]
    for j in range(i + 1, len(nums) - 1):
      working_target -= nums[j]
      current.append(nums[j])
      for k in range(j + 1, len(nums)):
        current.append(nums[k])
        if working_target - nums[k] == 0:
          # make code to put in duplicate set
          code = str(current[0])
          for n in range(1, len(current)):
            code += "&amp;amp;" + str(current[n])
          if code not in checked:
            output.append(current.copy())
            checked.add(code)
        current.pop()
      current.pop()
      working_target += nums[j]
    current.pop()
    working_target += nums[i]
  return output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is some sample driver code to test the method:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nums = [-1,0,1,2,-1,-4]
target = 0
print(sum_of_three(nums, target))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will give us the final output of &lt;code&gt;[[-1,-1,2],[-1,0,1]]&lt;/code&gt;. Notice how there are no duplicate triplets, even though there are two &lt;code&gt;-1&lt;/code&gt;s to make the second triplet. &lt;/p&gt;

&lt;h2&gt;
  
  
  5. Step Up Complexity: Sum of Four
&lt;/h2&gt;

&lt;p&gt;You were feeling pretty good, just finished Sum of Three. But can you next solve...sum of &lt;em&gt;four&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;Although it sounds more complex, conceptually, we can use the same brute force method. I know that our runtime will go from the terrible O(N&lt;sup&gt;3&lt;/sup&gt;) to the even worse O(N&lt;sup&gt;4&lt;/sup&gt;), but like I said earlier. It will still *run*. &lt;/p&gt;

&lt;p&gt;How will we achieve this? We can simply adjust our code from &lt;code&gt;sum_of_three&lt;/code&gt; by &lt;em&gt;adding another loop&lt;/em&gt;. Each loop starts at the previous index + 1 and ends progressively closer to the end of the list. Here is what they will look like: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; for i in range(len(nums) - 3):
    for j in range(i + 1, len(nums) - 2):
      for k in range(j + 1, len(nums) - 1):
        for m in range(k + 1, len(nums)):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In each loop, we'll follow the same steps as before: appending to &lt;code&gt;current&lt;/code&gt;, subtracting from the target, checking some stuff, and then undoing the previous actions. I'll save you some scrolling and post the method in full: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_four(nums, target):
  if len(nums) &amp;lt; 4:
    return []
  output = []
  current = []
  nums.sort()
  checked = set()
  for i in range(len(nums) - 3):
    working_target = target - nums[i]
    current.append(nums[i])
    for j in range(i + 1, len(nums) - 2):
      working_target -= nums[j]
      current.append(nums[j])
      for k in range(j + 1, len(nums) - 1):
        working_target -= nums[k]
        current.append(nums[k])
        for m in range(k + 1, len(nums)):
          current.append(nums[m])
          if working_target - nums[m] == 0:
            # make code to put in duplicate set
            code = str(current[0])
            for n in range(1, len(current)):
              code += "&amp;amp;" + str(current[n])
            if code not in checked:
              output.append(current.copy())
              checked.add(code)
          current.pop()
        current.pop()
        working_target += nums[k]
      current.pop()
      working_target += nums[j]
    current.pop()
  return output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This exactly matches our method for "Sum of Three", just with an extra loop. We can run the following driver code: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nums = [1,0,-1,0,-2,2, 0]
target = 0
print(sum_of_four(nums, target))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And our result is &lt;code&gt;[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]&lt;/code&gt;. It works!&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Sum of Five...and Beyond?
&lt;/h2&gt;

&lt;p&gt;You wrote "Sum of Three" and "Sum of Four"; you're feeling pretty confident. What if I told you next you need to solve...Sum of Five? &lt;/p&gt;

&lt;p&gt;No problem, you say. Just add another &lt;code&gt;for&lt;/code&gt; loop. But you might have noticed something. This looks a little repetitive: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for j in range(i + 1, len(nums) - 2):
  working_target -= nums[j]
  current.append(nums[j])
  for k in range(j + 1, len(nums) - 1):
    working_target -= nums[k]
    current.append(nums[k])
    for m in range(k + 1, len(nums)):
      current.append(nums[m])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And you're right. When we have repetitive code, a good practice is to write a method for it. So what if we wrote a recursive method to run each &lt;code&gt;for&lt;/code&gt; loop? Then, we could tell it how many numbers we want to sum together, and it will know how many nested loops to construct. &lt;/p&gt;

&lt;p&gt;We'll set up the method exactly we have as before, although this time, we take in an argument &lt;code&gt;k&lt;/code&gt; of how many numbers (triplet, quadruplet, etc.) to sum. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_k(nums, target, k):
  if len(nums) &amp;lt; k:
    return []
  output = []
  current = []
  nums.sort()
  checked = set()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we'll make a recursive method called &lt;code&gt;sum_helper()&lt;/code&gt; that accepts...pretty much every variable we have so far. Additionally, we need to know the previous index (for when we start the loop at &lt;code&gt;i + 1&lt;/code&gt;), which starts at 0. This method will alter the arrays, so we just need to call it and then afterwards, return &lt;code&gt;output&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  sum_helper(nums, target, k, output, checked, current, 0)
  return output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  7. Iteration in the Recursive Method
&lt;/h2&gt;

&lt;p&gt;Let's think about our approach for the recursive helper method. Each time, we're going to be subtracting from &lt;code&gt;k&lt;/code&gt;. After all, "Sum of Four" is just "Sum of Three" with an extra number attached. &lt;/p&gt;

&lt;p&gt;Our recursive method will need a base case. If &lt;code&gt;k&lt;/code&gt; is zero, we don't have to do anything. In this case, we'll simply &lt;code&gt;return&lt;/code&gt; out of the function. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  if k == 0:
    return
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If &lt;code&gt;k&lt;/code&gt; is greater than zero, we want to loop through &lt;code&gt;nums&lt;/code&gt;. We'll start at the index &lt;code&gt;prev&lt;/code&gt; and go until the end of the list - k + 1 (we get this by looking at the pattern in our previous solutions). &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for i in range(prev, len(nums) - k + 1):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's next? Look at our list: we append the current number to &lt;code&gt;current&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    current.append(nums[i])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You might think the next step is to subtract that number from the target, but we need to check something first. This &lt;code&gt;for&lt;/code&gt; loop needs to be universal for every iteration of &lt;code&gt;k&lt;/code&gt;, and we need to account for if this is the innermost loop. &lt;/p&gt;

&lt;p&gt;If this is the case, we need to check if the target minus the number is zero. Then we do exactly what we did before (you could probably copy paste with minimal edits) by adding to the set and if unique, add to the output. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if k == 1 and target - nums[i] == 0:
  # make code to put in duplicate set
  code = str(current[0])
  for n in range(1, len(current)):
    code += "&amp;amp;" + str(current[n])
  if code not in checked:
    output.append(current.copy())
    checked.add(code)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we can subtract from the working target and write our recursive case. But wait, we can do this all in one step! Here is the recursive call: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sum_helper(nums, target - nums[i], k - 1, output, checked, current, i + 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So &lt;code&gt;target&lt;/code&gt; moves, &lt;code&gt;k&lt;/code&gt; goes down 1, and the current index + 1 becomes the previous index &lt;code&gt;prev&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Finally, we have to undo our addition to &lt;code&gt;current&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;current.pop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's it! Together, here are our methods: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def sum_of_k(nums, target, k):
  if len(nums) &amp;lt; k:
    return []
  output = []
  current = []
  nums.sort()
  checked = set()
  sum_helper(nums, target, k, output, checked, current, 0)
  return output

def sum_helper(nums, target, k, output, checked, current, prev):
  if k == 0:
    return
  for i in range(prev, len(nums) - k + 1):
    current.append(nums[i])
    if k == 1 and target - nums[i] == 0:
      # make code to put in duplicate set
      code = str(current[0])
      for n in range(1, len(current)):
        code += "&amp;amp;" + str(current[n])
      if code not in checked:
        output.append(current.copy())
        checked.add(code)
    sum_helper(nums, target - nums[i], k - 1, output, checked, current, i + 1)
    current.pop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Our method is still pretty unwieldy, but we don't have to adjust it for every changing &lt;code&gt;k&lt;/code&gt;. The following driver code will work whether &lt;code&gt;k&lt;/code&gt; is 3, 4, or beyond!&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nums = [-1,0,1,2,-1,-4, -2]
target = 0
k = 4
print(sum_of_k(nums, target, k))
# -&amp;gt; [[-2, -1, 1, 2], [-1, -1, 0, 2]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Again, this is a brute force solution. The run time will be O(N&lt;sup&gt;k&lt;/sup&gt;), which is pretty bad if &lt;code&gt;k&lt;/code&gt; is large. This problem could probably be solved more elegantly with linear algebra, so if some of you are particularly knowledgeable on that front and come up with something, let me know in the comments!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl"&gt;&amp;lt;&amp;lt; #21 Tree Practice&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/sum_of_k.py"&gt;View Solution on GitHub&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>computerscience</category>
      <category>beginners</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Binary Tree Practice in Python: Mirror Tree</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Thu, 11 Mar 2021 00:07:15 +0000</pubDate>
      <link>https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl</link>
      <guid>https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la"&gt;&amp;lt;&amp;lt; #20 Breadth-First Search&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/mirror_tree.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/sum-of-three-sum-of-four-and-beyond-in-python-2224"&gt;#22 Sum of Three+ &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Flive.staticflickr.com%2F4811%2F45105769205_6847b4dc76_b.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Flive.staticflickr.com%2F4811%2F45105769205_6847b4dc76_b.jpg" alt="Trees mirrored in lake"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: FollowingNature on Flickr)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the previous article, we discussed the differences between breadth- and depth-first search for trees and graph problems. Today, we're going to actually look at a sample problem, and given our new toolbox of search strategies, figure out the best way to implement a solution.&lt;/p&gt;

&lt;p&gt;Here's the problem from &lt;a href="https://leetcode.com/problems/symmetric-tree/" rel="noopener noreferrer"&gt;LeetCode&lt;/a&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Given the root of a binary tree, check whether it is 
# a mirror of itself (i.e., symmetric around its center).
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's look at some examples.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree1.jpg" alt="tree example symmetrical"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: LeetCode)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Giving the function the root of the above tree would yield &lt;code&gt;True&lt;/code&gt;, since the values in the left half of the tree mirror the values in the right.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree2.jpg" alt="tree example unsymmetrical"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: LeetCode)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the above tree, the nodes with 3 are not organized to mirror each other. Passing the root would yield &lt;code&gt;False&lt;/code&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Strategy
&lt;/h2&gt;

&lt;p&gt;As with binary tree problems, the first thing we want to ask is if we should use &lt;a href="https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la"&gt;breadth- or depth-first search&lt;/a&gt;. At first glance, you might think BFS would make sense, seeing that all the nodes are the same across the first two levels. But once we look at the third level with the nodes &lt;code&gt;3, 4, 4, 3&lt;/code&gt;, suddenly, it gets more complicated. Instead, what if we split the tree into two halves and ran a depth-first-search on each half? Let's look at the first example again:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.leetcode.com%2Fuploads%2F2021%2F02%2F19%2Fsymtree1.jpg" alt="tree example symmetrical"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we were to look at the left half, depth-first-traversal would read the nodes in the order: &lt;code&gt;2, 3, 4&lt;/code&gt;. At the same time, we can travel down the right side of the tree and print the same &lt;code&gt;2, 3, 4&lt;/code&gt;. We then conclude the tree is symmetrical. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Setup
&lt;/h2&gt;

&lt;p&gt;The first thing we'll need is our &lt;code&gt;TreeNode&lt;/code&gt; class. As always, it will take &lt;code&gt;data&lt;/code&gt;, the value we want to store on the node, and then a &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; pointer, which are initialized to &lt;code&gt;None&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TreeNode:
  def __init__(self, data):
    self.data = data
    self.left = None
    self.right = None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we define our method, which takes in one value: the root node of the tree. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def is_mirror(root):
  pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Remember how we said we would split the tree into two halves, and then check the nodes in each half? We'll do that by calling a recursive helper method, &lt;code&gt;check_halves&lt;/code&gt;. This method takes a left and right node, which will be &lt;code&gt;root.left&lt;/code&gt; and &lt;code&gt;root.right&lt;/code&gt; to start.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def is_mirror(root):
  return check_halves(root.left, root.right)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  3. Traversal
&lt;/h2&gt;

&lt;p&gt;As with most tree traversals, we'll be using recursion. Start by defining our helper method that takes in a &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; tree.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def check_halves(left, right):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What is our base case? The simplest example would be a tree with only the root node, whose left and right halves are both &lt;code&gt;None&lt;/code&gt;. In this case, we return &lt;code&gt;True&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def check_halves(left, right):
  if not left and not right:
    return True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's next? We want to check that there are both a left and right node, and that their values match. These can be put in the same if statement, but I'll separate them for clarity.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def check_halves(left, right):
  if not left and not right:
    return True
  if left and right:
    if left.data == right.data:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we recurse! Here, we'll do a depth-first traversal on the left and right halves of the tree. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      left_half = check_halves(left.left, right.right) 
      right_half = check_halves(left.right, right.left)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then, we check to see if they are both &lt;code&gt;True&lt;/code&gt;. This can be achieved with an &lt;code&gt;and&lt;/code&gt; statement. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      return left_half and right_half
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we return the False if the previous &lt;code&gt;if&lt;/code&gt; condition was not met. Altogether, our helper method looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def check_halves(left, right):
  if not left and not right:
    return True
  if left and right:
    if left.data == right.data:
      left_half = check_halves(left.left, right.right) 
      right_half = check_halves(left.right, right.left)
      return left_half and right_half
  return False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  4. Test it Out
&lt;/h2&gt;

&lt;p&gt;The following code will build the tree from the example. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree1 = TreeNode(1)
tree1.left = TreeNode(2)
tree1.right = TreeNode(2)
tree1.left.left = TreeNode(3)
tree1.right.right = TreeNode(3)
tree1.left.right = TreeNode(4)
tree1.right.left = TreeNode(4)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we just have to call &lt;code&gt;print(is_mirror(tree1))&lt;/code&gt; and it will print &lt;code&gt;True&lt;/code&gt;. Success!&lt;/p&gt;

&lt;p&gt;Let's try a tree that isn't symmetrical, like the second example. The two nodes with the value &lt;code&gt;3&lt;/code&gt; aren't positioned to mirror each other. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree2 = TreeNode(1)
tree2.left = TreeNode(2)
tree2.right = TreeNode(2)
tree2.left.left = TreeNode(3)
tree2.right.left = TreeNode(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Printing &lt;code&gt;is_mirror(tree2)&lt;/code&gt; should give us &lt;code&gt;False&lt;/code&gt;. The same will work if we change any values in the first tree so that they don't match left and right. &lt;/p&gt;

&lt;p&gt;That's it for this week, I hope this was a good lesson on how to use DFS concepts to solve a Binary Tree problem. In a future article, we'll take a look at a problem where a breadth first approach would work better. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la"&gt;&amp;lt;&amp;lt; #20 Breadth-First Search&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/mirror_tree.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/sum-of-three-sum-of-four-and-beyond-in-python-2224"&gt;#22 Sum of Three+ &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>More Python Binary Trees: What is Breadth vs Depth First Search?</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Tue, 23 Feb 2021 04:44:51 +0000</pubDate>
      <link>https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la</link>
      <guid>https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208"&gt;&amp;lt;&amp;lt; #19: JS Arrays&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/level_of_min_sum.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl"&gt;#21: Mirror Tree &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--v8ZGrz4F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.48days.com/wp-content/uploads/2015/06/Wheat-Field-1024x683.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--v8ZGrz4F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.48days.com/wp-content/uploads/2015/06/Wheat-Field-1024x683.jpg" alt="field of wheat"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Fq1CaGWl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deeperblue.com/wp-content/uploads/2017/08/France-Ressel-Shallow-route.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Fq1CaGWl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deeperblue.com/wp-content/uploads/2017/08/France-Ressel-Shallow-route.jpg" alt="cave diver"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;IRL Breadth and Depth. (Images: 48days.com, deeperblue.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Christmas is over, but the classic data structure Binary Trees is forever. At least, technical hiring managers seem to think so. And when you're asked to solve a binary tree problem on an interview, the first thing your interviewer will want to know is this: breadth or depth first? &lt;/p&gt;

&lt;h2&gt;
  
  
  What's the difference?
&lt;/h2&gt;

&lt;p&gt;Breadth First Search and Depth First Search, or BFS and DFS, are exactly as they sound--it's about the order of nodes we visit when traversing a tree. Depth first travels down the tree before traveling across, and breadth is just the opposite--start with the root and work down to its children, and then its children's children, and so on. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZlV3vMEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media.geeksforgeeks.org/wp-content/cdn-uploads/2009/06/tree12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZlV3vMEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media.geeksforgeeks.org/wp-content/cdn-uploads/2009/06/tree12.gif" alt="binary tree"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: GeeksForGeeks)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For example, in the above tree, a BFS approach would yield 1, 2, 3, 4, 5. &lt;/p&gt;

&lt;p&gt;For DFS, there are multiple possible outcomes depending on if we do a Pre-, Post-, or In- order traversal. For example, Pre-order would yield 1, 2, 4, 5, 3. We've covered these three traversals in &lt;a href="https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch"&gt;this article&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing Breadth First Search in Python
&lt;/h2&gt;

&lt;p&gt;Let's look at how we would do a BFS in Python. Start by defining our TreeNode class, which simply needs a value, and a left and right pointer.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TreeNode:
  def __init__(self, value):
    self.value = value
    self.left = None
    self.right = None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  1. Strategy
&lt;/h3&gt;

&lt;p&gt;Here's how we will approach traversing each node by level:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the full height of the tree from root to farthest leaf.&lt;/li&gt;
&lt;li&gt;Loop over each level (ending with the height)&lt;/li&gt;
&lt;li&gt;Traverse to each level and print all the nodes on that level.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  2. Find the Height of the Tree
&lt;/h3&gt;

&lt;p&gt;In order to traverse over each level, we need to know how many levels there are in the tree. We'll write a method to traverse the tree and find its height.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def height(node):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You guessed it--this is going to be a recursive method, as are most binary tree traversals. Let's think of our base case. The simplest case is if we're given a null root, in which case the height is 0. You might say a node with no children is the simplest case, but then we have to check for its children, which adds to the complexity. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def height(node):
  if not node:
    return 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What next? We have the left and right halves of the tree to traverse. So we'll call the &lt;code&gt;height()&lt;/code&gt; method on those halves and save them to two variables, &lt;code&gt;l_height&lt;/code&gt; and &lt;code&gt;r_height&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def height(node):
  if not node:
    return 0
  l_height = height(node.left) 
  r_height = height(node.right) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Which height do we return, left or right? Why, the higher one, of course! So we'll take the &lt;code&gt;max()&lt;/code&gt; of both values, and return that. Don't forget to add 1 for the current node. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def height(node):
  if not node:
    return 0
  l_height = height(node.left) 
  r_height = height(node.right) 

  return max(l_height, r_height) + 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  3. Loop Over Each Level
&lt;/h3&gt;

&lt;p&gt;Now that we have our height, we're ready to begin writing our breadth first traversal method. The only argument it takes is the &lt;code&gt;root&lt;/code&gt; node. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def breadth_first(root):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we get our height. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def breadth_first(root):
  h = height(root)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we loop over the height of the tree. For each height, we're going to call a helper function, &lt;code&gt;print_level()&lt;/code&gt; which takes the root node and the level. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def breadth_first(root):
  h = height(root)
  for i in range(h):
    print_level(root, i)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  4. Traverse the Tree
&lt;/h3&gt;

&lt;p&gt;For each level, we're going to traverse down to the nodes at that level and print them. This will be achieved through our helper function. It takes in two arguments, the root node and the current level.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_level(root, level):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For this method, the level initially refers to the index &lt;code&gt;i&lt;/code&gt; from the &lt;code&gt;for&lt;/code&gt; loop. To traverse to the tree, we're going to recursively go down each level, subtracting from &lt;code&gt;i&lt;/code&gt; each time until we hit level 0. This means we're at our level of interest, and we can print the nodes. &lt;/p&gt;

&lt;p&gt;Again, our base case is if the root is null. This method only prints the tree, and doesn't return anything, so we'll simply &lt;code&gt;return&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_level(root, level):
  if not root:
    return
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, if our level is 0, i.e. the level we're interested in, we want to print the value at that node. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_level(root, level):
  if not root:
    return
  if level == 0:
    print(root.value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, if our level is greater than zero, that means we have to traverse down the tree. We call our recursive method on the left and right halves of the tree. Remember to subtract 1 from &lt;code&gt;level&lt;/code&gt; in both function calls. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_level(root, level):
  if not root:
    return
  if level == 0:
    print(root.value)
  elif level &amp;gt; 0:
    print_level(root.left, level - 1)
    print_level(root.right, level - 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's it! It took three separate methods, but we're finally able to do a breadth-first traversal of the tree. &lt;/p&gt;

&lt;h3&gt;
  
  
  5. Test it Out
&lt;/h3&gt;

&lt;p&gt;First, make a tree using our &lt;code&gt;TreeNode&lt;/code&gt; class. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree = TreeNode(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZlV3vMEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media.geeksforgeeks.org/wp-content/cdn-uploads/2009/06/tree12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZlV3vMEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media.geeksforgeeks.org/wp-content/cdn-uploads/2009/06/tree12.gif" alt="binary tree"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: GeeksForGeeks)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Next, populate the rest of the tree. The following is to populate for the tree in the above image. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree.left = TreeNode(2)
tree.right = TreeNode(3)
tree.left.left = TreeNode(4)
tree.left.right = TreeNode(5) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we run our method. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;breadth_first(tree)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This should print out 1, 2, 3, 4, 5. We've successfully traversed the tree!&lt;/p&gt;

&lt;p&gt;If you have any ideas for problems or data structures you want to see covered on here, let me know in the comments! Thanks for reading.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208"&gt;&amp;lt;&amp;lt; #19: JS Arrays&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/level_of_min_sum.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/binary-tree-practice-in-python-mirror-tree-1hl"&gt;#21: Mirror Tree &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>computerscience</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Javascript Fun(ctions)! Explore the 3 Hottest Array Methods: Map, Filter, and Reduce</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Tue, 09 Feb 2021 03:00:01 +0000</pubDate>
      <link>https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208</link>
      <guid>https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd"&gt;&amp;lt; #18 Webcrawling&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/js-specific/arrUtilities.js"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la"&gt;#20 Binary Trees II &amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LzAZUovs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.codeanalogies.com/img/funcblog/codeblock1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LzAZUovs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.codeanalogies.com/img/funcblog/codeblock1.png" alt="js function to make a sandwhich"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: codeanalogies.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Python will always be my first love, being the first programming language  I ever learned (sorry, Java, not counting you). Its versatility and built-in librarys make for a wide range of applications, including data structures and algorithms. JavaScript on the other hand, being functional instead of object-oriented, is less so-equipped. However, being the de-facto language of the internet, its applications are widespread on the front end, including high-tech frameworks like React and Vue. &lt;/p&gt;

&lt;p&gt;You might be wondering, what kind of questions might a company ask on a JavaScript technical interview? Functions! I know, shocker, the key to functional programming is functions. So today, we'll look at three built-in array methods and try to implement them on our own. By doing so, I hope this will help you get more familiar with using these hip "callback" things that tend to pop up everywhere in JavaScript coding.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. &lt;code&gt;.map()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The Array.map() function can be called on an array to, simpy put, take each item and replace it (or "map" it) with something else. This is commonly used in applications like React to turn raw data, like&lt;code&gt;["milk", "eggs", "butter"]&lt;/code&gt; into something more html-friendly, such as list items: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    "&amp;lt;li&amp;gt;milk&amp;lt;/li&amp;gt;", 
    "&amp;lt;li&amp;gt;eggs&amp;lt;/li&amp;gt;", 
    "&amp;lt;li&amp;gt;butter&amp;lt;/li&amp;gt;"
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We could achieve this by calling &lt;code&gt;.map()&lt;/code&gt;, which takes a callback function as an argument:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let groceries = ["milk", "eggs", "butter"];
let makeList = (item) =&amp;gt; {
    return (
        `&amp;lt;li&amp;gt;${item}&amp;lt;/li&amp;gt;`
    );
}

console.log(groceries.map(makeList));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;More on the map function &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"&gt;here&lt;/a&gt;. So how would we build it on our own?&lt;/p&gt;

&lt;p&gt;We'll define our homegrown map funciton as &lt;code&gt;myMap&lt;/code&gt;, and it will take two arguments, the array &lt;code&gt;arr&lt;/code&gt; and the callback function &lt;code&gt;cb&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myMap(arr, cb) {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;JavaScript utility methods usually return a new object instead of altering the original one. Here, we'll make a new empty array and push items onto it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myMap(arr, cb) {
    newArr = [];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's next? We need to loop over our array. The syntax for a simple &lt;code&gt;for&lt;/code&gt; loop traversing an array is probably familiar to you by now.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myMap(arr, cb) {
  newArr = [];
  for (i = 0; i &amp;lt; arr.length; i++) {

  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Remember the function of &lt;code&gt;map&lt;/code&gt;. We want to get the item and call the function on it to get its new value. You can call the callback function simply by putting a pair of parentheses after it and passing in arguments, which is the value at index &lt;code&gt;i&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for (i = 0; i &amp;lt; arr.length; i++) {
    let newValue = cb(arr[i]);

  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once we get that new value, we want to push it onto our new array.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for (i = 0; i &amp;lt; arr.length; i++) {
    let newValue = cb(arr[i]);
    newArr.push(newValue);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we return our new array (outside of the loop). &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myMap(arr, cb) {
  newArr = [];
  for (i = 0; i &amp;lt; arr.length; i++) {
    let newValue = cb(arr[i]);
    newArr.push(newValue);
  }
  return newArr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we're done! To try it out, we can try making our grocery list again:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(myMap(groceries, makeList));
// =&amp;gt; [ '&amp;lt;li&amp;gt;milk&amp;lt;/li&amp;gt;', '&amp;lt;li&amp;gt;eggs&amp;lt;/li&amp;gt;', '&amp;lt;li&amp;gt;butter&amp;lt;/li&amp;gt;' ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  2. &lt;code&gt;.filter()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The Array.filter() method takes a callback which returns a boolean, and if that boolean is false, removes that item from the array. Essentially, it filters out unimportant elements based on the function's criteria.&lt;/p&gt;

&lt;p&gt;For example, we might want to remove even numbers from a list. We have our list, &lt;code&gt;nums&lt;/code&gt;, and a function &lt;code&gt;isOdd&lt;/code&gt; that returns &lt;code&gt;true&lt;/code&gt; if the given number is odd. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums = [1, 2, 3, 4, 5];
let isOdd = (num) =&amp;gt; {
  return num % 2 === 1;
}

console.log(nums.filter(isOdd));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The result should give us the array with only the odd numbers: &lt;code&gt;[1, 3, 5]&lt;/code&gt;. I'll link the &lt;code&gt;filter&lt;/code&gt; documentation &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter"&gt;here&lt;/a&gt;. Now let's write it on our own.&lt;/p&gt;

&lt;p&gt;Start by defining the function, which takes in an array and a callback function. Again, we'll make a new array, and then write a &lt;code&gt;for&lt;/code&gt; loop to loop through the original array.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myFilter(arr, cb) {
    let newArr = [];
    for (let i=0; i &amp;lt; arr.length; i++) {

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;First, we get the value at that index. Then, we call our callback function and see if it returns &lt;code&gt;true&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for (let i=0; i &amp;lt; arr.length; i++) {
    let value = arr[i];
    if (cb(value)) {

    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you're new to programming, you'll notice that &lt;code&gt;if&lt;/code&gt; statements check for truthy or falsey values, so we can simply say &lt;code&gt;if (cb(value))&lt;/code&gt; instead of &lt;code&gt;if (cb(value) === true)&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Finally, we push the value onto the new array if the callback returns true. Don't forget to return the new array at the end of your function.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myFilter(arr, cb) {
  let newArr = [];
  for (let i=0; i &amp;lt; arr.length; i++) {
    let value = arr[i];
    if (cb(value)) {
      newArr.push(value);
    }
  }
  return newArr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can try out our filter method by passing it the &lt;code&gt;nums&lt;/code&gt; array and &lt;code&gt;isOdd()&lt;/code&gt; function from earlier. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(myFilter(arr3, isOdd));
// =&amp;gt; [ 1, 3, 5 ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There we go! It looks like our method successfully filtered out the even values.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. &lt;code&gt;.reduce()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;This function might be one you didn't encounter in class (at least, not for me). Essentially, it takes all the elements in an array and reduces them down to one value. For example, let's say we want to multiply together all the numbers in our array.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function mult(prev, curr) {
  return prev * curr;
}

// let nums = [1, 2, 3, 4, 5];
console.log(nums.reduce(mult)); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The console should print &lt;code&gt;120&lt;/code&gt;, which is the product of all those numbers. You'll notice that functions used by &lt;code&gt;.reduce()&lt;/code&gt; usually take two arguments: a previous value &lt;code&gt;prev&lt;/code&gt; and a current value &lt;code&gt;curr&lt;/code&gt;. This effectively chains all the values together by calling the callback function repeatedly on the previous value. We'll stick to this basic functionality for now, but if you look at the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"&gt;documentation&lt;/a&gt;, &lt;code&gt;.reduce()&lt;/code&gt; can take a couple other arguments. &lt;/p&gt;

&lt;p&gt;Let's try it on our own. The function will take in an array and a callback, as usual. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myReduce(arr, cb) {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Instead of returning an array, we'll return a single value. Let's call it &lt;code&gt;final&lt;/code&gt;. What should the initial value be? If we're multiplying every number together, we could perhaps start with the first one, and multiply all the others to it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myReduce(arr, cb) {
  let final = arr[0];

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, the &lt;code&gt;for&lt;/code&gt; loop. Since we've already accounted for the first value, we'll start our loop at index 1. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 1; i &amp;lt; arr.length; i++) {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then, we'll reassign &lt;code&gt;final&lt;/code&gt; to the result of the callback function. Remember, our callback takes in a previous and current value. The previous will be the &lt;code&gt;final&lt;/code&gt; value we have so far, and the current value is the value at index &lt;code&gt;i&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for (let i = 1; i &amp;lt; arr.length; i++) {
    final = cb(final, arr[i]);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we can return our final value. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myReduce(arr, cb) {
  let final = arr[0];
  for (let i = 1; i &amp;lt; arr.length; i++) {
    final = cb(final, arr[i]);
  }
  return final;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's try it out. Pass in the &lt;code&gt;nums&lt;/code&gt; array and &lt;code&gt;mult&lt;/code&gt; function, and we should get the same number as before, 120. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(myReduce(nums, mult));
// =&amp;gt; 120
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's it, we've explored and implemented three JavaScript array methods. I hope this helped you gain a better understanding of callback functions, enough to ace that JavaScript interview. If you're hungry for more, check out &lt;a href="https://johnresig.com/apps/learn/"&gt;these lessons&lt;/a&gt; on advanced JS topics. See you next time!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd"&gt;&amp;lt; #18 Webcrawling&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/js-specific/arrUtilities.js"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-binary-trees-what-is-breadth-vs-depth-first-search-25la"&gt;#20 Binary Trees II &amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>functional</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Web Crawling in Python: Dive Into Beautiful Soup</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Mon, 25 Jan 2021 23:43:06 +0000</pubDate>
      <link>https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd</link>
      <guid>https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo"&gt;&amp;lt; Week 17: Knapsack&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/web_scraping.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208"&gt;Week 19: JS Array Functions &amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimg.sndimg.com%2Ffood%2Fimage%2Fupload%2Fc_thumb%2Cq_80%2Cw_562%2Ch_316%2Fv1%2Fimg%2Frecipes%2F11%2F21%2F33%2FpicZciKrq.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimg.sndimg.com%2Ffood%2Fimage%2Fupload%2Fc_thumb%2Cq_80%2Cw_562%2Ch_316%2Fv1%2Fimg%2Frecipes%2F11%2F21%2F33%2FpicZciKrq.jpg" alt="alphabet soup"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: Food.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;What is Beautiful Soup? Something your mom makes for you on a cold January day? I hope so. Beautiful Soup is a webscraping Python library, and however difficult you thought webscraping would be, Beatiful Soup makes it so much easier. For instance, I used it on one &lt;a href="https://github.com/erik-hei/lyrical" rel="noopener noreferrer"&gt;project&lt;/a&gt;, when I had to scrape the Genius website, since their API doesn't actually provide song lyrics (I know right? You had one job, Genius). &lt;/p&gt;

&lt;p&gt;Let's look at a sample technical interview question:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Crawl a webpage and print the most common word with 
# the count of that word.

# Page to crawl:
# https://en.wikipedia.org/wiki/Apple_Inc.

# Only words from the section “history” should be accounted for.

# Example of the expected result
#     # of occurrences
# The 205
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We're given Apple's Wikipedia page, and we want to find the most common word in the "history" section. So let's get started. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Setup and Installation
&lt;/h2&gt;

&lt;p&gt;First we need to import Beautiful Soup. Install from the command line via &lt;code&gt;pip3 install bs4&lt;/code&gt; (or however you have pip configured). Check the &lt;a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noopener noreferrer"&gt;documentation&lt;/a&gt; if you're having issues with installation. &lt;/p&gt;

&lt;p&gt;Then, let's require our library at the top of the code. Here's everything we'll need:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bs4 import BeautifulSoup, Tag
import requests

from collections import defaultdict
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we're ready to define our function.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_most_common():
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  2. Get the Page
&lt;/h2&gt;

&lt;p&gt;Let's get our page and parse it with Beautiful soup. To get the page, we use the &lt;code&gt;requests&lt;/code&gt; library:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  page = requests.get("https://en.wikipedia.org/wiki/Apple_Inc.")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we parse the page text using Beautiful Soup.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  soup = BeautifulSoup(page.text, "html.parser")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;How do we get just the history section? We have to take a look at the HTML of the page. There's a lot of random-looking gibberish, which I've tried to clean up:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2&amp;gt;
    &amp;lt;span class="mw-headline" id="History"&amp;gt;History&amp;lt;/span&amp;gt;
&amp;lt;/h2&amp;gt;
&amp;lt;div ...&amp;gt;...&amp;lt;/div&amp;gt;
&amp;lt;div ...&amp;gt;...&amp;lt;/div&amp;gt;
&amp;lt;h3&amp;gt;
    &amp;lt;span ...&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;span class="mw-headline" id="1976–1984:_Founding_and_incorporation"&amp;gt;1976–1984: Founding and incorporation&amp;lt;/span&amp;gt;
&amp;lt;/h3&amp;gt;
.
.
.
&amp;lt;p&amp;gt;Apple Computer Company was founded on April 1, 1976, by &amp;lt;a href="/wiki/Steve_Jobs" title="Steve Jobs"&amp;gt;Steve Jobs&amp;lt;/a&amp;gt;...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For some reason, Wikipedia seems to have all their content in one div. This means that the "history" section is not its own div, but a header and some stuff inside a parent div, which contains all the sections. To get only the history section, the best we can do for now is to just grab that header and everything after it. We grab the &lt;code&gt;&amp;lt;span&amp;gt;&lt;/code&gt; tag with ID "History", and then go to its parent, the &lt;code&gt;&amp;lt;h2&amp;gt;&lt;/code&gt;. To get everything after it, we can use the BeautifulSoup notation, &lt;code&gt;next_siblings&lt;/code&gt;. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  history = soup.find(id="History").parent.next_siblings
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  3. Count the Words
&lt;/h2&gt;

&lt;p&gt;Let's initialize a couple variables. We'll need the most common word and the number of times it appears. We'll also use a dictionary to store the count of each word. If you've been following this blog, you've probably guessed that we'll use a default dicitonary for this (if you don't remember, we can set the dictionary's default type to integers. That way, if we access a key that doesn't exist, the default value is already 0). &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  max_count = 0
  max_word = ""
  dd = defaultdict(int)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, we're ready to crawl. Let's loop through &lt;code&gt;history&lt;/code&gt; and look at each element, &lt;code&gt;elem&lt;/code&gt;. However, Beautiful Soup sometimes returns something called a "Navigable String" instead of an element. We'll filter out everything that isn't an element using the &lt;code&gt;isinstance()&lt;/code&gt; method from our library.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for elem in history:
    if isinstance(elem, Tag):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's think of what happens next. We need to look at the text for each element in &lt;code&gt;history&lt;/code&gt;, and count the instance of each word. However, remember, we need to stop when we're no longer in the history section. The next section is the same div, but starts with an &lt;code&gt;&amp;lt;h2&amp;gt;&lt;/code&gt; tag. Then, we can end the function by printing the most common word and its count. I'll return &lt;code&gt;max_count&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for elem in history:
    if isinstance(elem, Tag):
      if elem.name == "h2":
        print(max_word, "is the most common, appearing", max_count, "times.")
        return max_count
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But what if it's not the end of the section? We need to get the text by calling the BeautifulSoup &lt;code&gt;get_text()&lt;/code&gt; method, and then split it into words by calling &lt;code&gt;split()&lt;/code&gt; on each space. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      words = elem.get_text().split()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's next? Loop through each word and update its count in the dictionary. Since we're using a default dictionary, we don't have to check to see if the word is already in there before adding 1 to it. Also, don't forget to update the &lt;code&gt;max_word&lt;/code&gt; and &lt;code&gt;max_count&lt;/code&gt; if we find a word that's more common than what we had previously. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      for word in words:
        dd[word] += 1
        if dd[word] &amp;gt; max_count:
          max_count = dd[word]
          max_word = word 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's it! The code should work...unless Wikipedia changes the layout of their site. Let's add a final check at the end in case that happens. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bs4 import BeautifulSoup, Tag
import requests

from collections import defaultdict

def find_most_common():
  page = requests.get("https://en.wikipedia.org/wiki/Apple_Inc.")
  soup = BeautifulSoup(page.text, "html.parser")
  history = soup.find(id="History").parent.next_siblings
  max_count = 0
  max_word = ""
  dd = defaultdict(int)

  for elem in history:
    if isinstance(elem, Tag):
      if elem.name == "h2":
        print(max_word, "is the most common, appearing", max_count, "times.")
        return max_count
      words = elem.get_text().split()
      for word in words:
        dd[word] += 1
        if dd[word] &amp;gt; max_count:
          max_count = dd[word]
          max_word = word

  return "Error"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Try it out
&lt;/h2&gt;

&lt;p&gt;This function prints the result, so we can simply run it with &lt;code&gt;find_most_common()&lt;/code&gt;. Running the code gives us the result:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;the is the most common, appearing 328 times.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And there you have it! Granted, this function only works for this specific page, at the time of writing this--the main problem with web crawling is that it can break if the website owner alters their content in the slightest fashion. We also didn't account for casing or punctuation, something you may want to try and implement on your own. Just a few things to think about. See you next time!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo"&gt;&amp;lt; Week 17: Knapsack&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/web_scraping.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/javascript-fun-ctions-explore-the-3-hottest-array-methods-map-filter-and-reduce-208"&gt;Week 19: JS Array Functions &amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Help Pierre the Py Pirate Solve this Knapsack Problem!</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Thu, 14 Jan 2021 07:41:21 +0000</pubDate>
      <link>https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo</link>
      <guid>https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj"&gt;&amp;lt;&amp;lt; Week 16: Find Substrings&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/knapsack.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd"&gt;Week 18: Webcrawling &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NVBCS1VF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.thoughtco.com/thmb/n1YuGNA1U0z4ubSMMIc_-y9QQNw%3D/3865x2576/filters:fill%28auto%2C1%29/buried-pirates-treasure-chest-157583040-5b5630f7c9e77c005b40d079.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NVBCS1VF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.thoughtco.com/thmb/n1YuGNA1U0z4ubSMMIc_-y9QQNw%3D/3865x2576/filters:fill%28auto%2C1%29/buried-pirates-treasure-chest-157583040-5b5630f7c9e77c005b40d079.jpg" alt="treasure chest"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;There is no love like that between a pirate and his booty. (Image: ThoughtCo)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Remember when quarantine began, and all tech companies had to go remote? The joy we had during those first months...learning new pranks on Zoom! Students from my class will remember when I changed my inactive screen name to Pierre the Py Pirate (yes, Mac, it was me). There's nothing to break up a lecture on SQL models like a sudden "Ahoy!" from Pierre in the Zoom chat. We had a lot of fun in that class. &lt;/p&gt;

&lt;p&gt;This is a problem I think Pierre would enjoy, as a pirate going about his pirate-y business. Let's take a look:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# A thief finds much more loot than he can fit in his knapsack.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Wait! Let me re-write this in terms Pierre would understand.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Pierre the Py Pirate has plundered new booty! But alas, he
# can only fit a limited amount in the cargo hold of his ship.
# Help him to find the most valuable combination of items 
# assuming that any fraction of a loot item can be kept.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  1. Setup
&lt;/h3&gt;

&lt;p&gt;Let's say, for the problem, we're given two arrays: one which has the weight of each item, and one with each value. We're also given the capacity of the cargo hold. Simple enough; let's set up the method:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def knapsack(cap, values, weights):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  2. Strategy
&lt;/h3&gt;

&lt;p&gt;Think about how you would approach this problem if you were Pierre. Let's say he has found a diamond ring, which weighs little but is worth much, and a sack of flour, which weighs a lot, but isn't worth so much. He'd want to keep the ring first, and then keep whatever flour can fill the rest of the space. So we'll start by sorting the items by their value-per-weight, and then add the most valuable items first until our capacity is reached. &lt;/p&gt;
&lt;h3&gt;
  
  
  3. Make the Sorted List of Items
&lt;/h3&gt;

&lt;p&gt;We'll start by making a new &lt;code&gt;items&lt;/code&gt; list, where we'll put the sorted list of items. Then, we'll loop over the &lt;code&gt;values&lt;/code&gt; list (or the &lt;code&gt;weights&lt;/code&gt; list, since they're the same length). For each item, we'll store the value-per-item as &lt;code&gt;vpw&lt;/code&gt;, and we'll also keep the weigth (more on this later).&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def knapsack(cap, values, weights):
  items = []
  for i in range(len(values)):
    itemInfo = {
      'vpw': values[i]/weights[i],
      'weight': weights[i]
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we have to add the item to the &lt;code&gt;items&lt;/code&gt; list. However, we can't just tack it onto the end--this is a &lt;em&gt;sorted&lt;/em&gt; list, sorted by the &lt;code&gt;vpw&lt;/code&gt;. So, we'll traverse the &lt;code&gt;items&lt;/code&gt; list, checking each &lt;code&gt;vpw&lt;/code&gt; against the current item to see where we should put it. &lt;/p&gt;

&lt;p&gt;First, if there are no items in the list, we have nothing to check it against, so we'll just add it.     &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if len(items) == 0:
      items.append(itemInfo)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we traverse the list. We don't know the exact number of times we'll need to move, just so long as the &lt;code&gt;vpw&lt;/code&gt; of our current item is less than the one in the list, we need to move closer to the end. A &lt;code&gt;while&lt;/code&gt; loop would work great. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    else:
      k = 0
      while k &amp;lt; len(items) and items[k]['vpw'] &amp;gt; itemInfo['vpw']:
        k += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Okay, now our index &lt;code&gt;k&lt;/code&gt; should be pointing where the new item should go. We can use the Python &lt;code&gt;insert()&lt;/code&gt; method to put it there. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    else:
      k = 0
      while k &amp;lt; len(items) and items[k]['vpw'] &amp;gt; itemInfo['vpw']:
        k += 1
      items.insert(k, itemInfo)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  4. Add Items from the Sorted List to the "Knapsack"
&lt;/h3&gt;

&lt;p&gt;Now it's time to fill up Pierre's cargo hold. As stated earlier, we're going to go through our list of items, conveniently sorted from most value-per-weight to least, and add each one until our capacity is filled up. &lt;/p&gt;

&lt;p&gt;Let's make some new variables. &lt;code&gt;total&lt;/code&gt; is what we're returning, the final value of Pierre's loot. Additionally, we'll make a &lt;code&gt;cap_left&lt;/code&gt; variable to keep track of how much capacity is remaining after each item is added. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  total = 0
  cap_left = cap
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, we'll loop through the items. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for item in items:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For each item, we'll first check to see if it fits. If so, we add its value to &lt;code&gt;total&lt;/code&gt; (the value can be found by multiplying the items &lt;code&gt;weight&lt;/code&gt; by the &lt;code&gt;vpw&lt;/code&gt;). Don't forget to subract the weight from &lt;code&gt;cap_left&lt;/code&gt;!&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if cap_left - item['weight'] &amp;gt;= 0 :
  total += item['weight'] * item['vpw']
  cap_left -= item['weight']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's say we've added a few items, and there's still room, but not enough to add the next whole item. The prompt says we can add a fraction of an item! To do this, we'll just check to see that there's some remaining capacity, and then calculate how much to add to total. There's some math involved; essentially we multiply the item's &lt;code&gt;vpw&lt;/code&gt; by the remaining capacity. Then, after we've added it to the total, &lt;code&gt;cap_left&lt;/code&gt; should be set to 0. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    elif cap_left &amp;gt; 0:
      total += item['vpw'] * cap_left
      cap_left = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;All that's left is to &lt;code&gt;return total&lt;/code&gt;! Altogether: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def knapsack(cap, values, weights):
  items = []
  for i in range(len(values)):
    itemInfo = {
      'vpw': values[i]/weights[i],
      'weight': weights[i]
    }
    if len(items) == 0:
      items.append(itemInfo)
    else:
      k = 0
      while k &amp;lt; len(items) and items[k]['vpw'] &amp;gt; itemInfo['vpw']:
        k += 1
      items.insert(k, itemInfo)
  total = 0
  cap_left = cap
  for item in items:
    if cap_left - item['weight'] &amp;gt;= 0 :
      total += item['weight'] * item['vpw']
      cap_left -= item['weight']
    elif cap_left &amp;gt; 0:
      total += item['vpw'] * cap_left
      cap_left = 0
  return total
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  5. Try it Out
&lt;/h3&gt;

&lt;p&gt;Let's say Pierre has plundered three items, a barrel of rum, a sack of flour, and a roll of silk. He has room for 60 lbs in his ship. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cap = 60
values = [60, 100, 120]
weights = [20, 50, 30]

print(knapsack(cap, values, weights))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The silk has the highest VPW at 4 gold/lb, and next is rum at 3 and flour at 2. The silk gets added first, then the rum, and finally we have 10 lbs left to fit the flour. 10 lbs of flour is valued at 20 gold, so that makes for a return total of 200 gold pieces. Yarrr!&lt;/p&gt;

&lt;p&gt;There are many ways of solving this problem. Let me know in the comments if you think you found a better way!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj"&gt;&amp;lt;&amp;lt; Week 16: Find Substrings&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/knapsack.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/web-crawling-in-python-dive-into-beautiful-soup-4bdd"&gt;Week 18: Webcrawling &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codenewbie</category>
      <category>beginners</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>More Python Strings: Can You Solve This *More* Difficult String Problem?</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Thu, 07 Jan 2021 04:29:04 +0000</pubDate>
      <link>https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj</link>
      <guid>https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch"&gt;&amp;lt;&amp;lt; Week 15: Binary Trees&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/find_strings.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo"&gt;Week 17: Knapsack &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oGvccqdr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://static.turbosquid.com/Preview/2020/03/24__10_02_23/alphabet_004_0000.jpg0DC9B5C0-7C0E-481F-81BD-F51D6005E5DALarge.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oGvccqdr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://static.turbosquid.com/Preview/2020/03/24__10_02_23/alphabet_004_0000.jpg0DC9B5C0-7C0E-481F-81BD-F51D6005E5DALarge.jpg" alt="Alphabet magnets"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: TurboSquid.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a problem that pops up now and again on various daily-coding-challenge platforms, like &lt;a href="https://www.hackerrank.com/challenges/find-strings/problem?h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen&amp;amp;h_r=next-challenge&amp;amp;h_v=zen"&gt;this problem on HackerRank&lt;/a&gt;: given a string, find all the possible combinations of letters within that string. This is sometimes called "substrings," or if a series of lists is returned, "power sets." Let's look at one example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Given a string, return a sorted list of all 
# unique possible substrings.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For example, the string &lt;code&gt;'abc'&lt;/code&gt; would yield the list &lt;code&gt;['a', 'ab', 'abc', 'ac', 'b', 'bc', 'c']&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's start with defining our method. It takes in a string, which we'll call &lt;code&gt;word&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_substrings(word):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, let's think about our approach. We'll need a data structure to store all our new substrings. In the end, we'll have to return a list, but remember what it said in the prompt: &lt;em&gt;unique&lt;/em&gt; substrings. So if we have the string &lt;code&gt;'aa'&lt;/code&gt;, we don't want to add &lt;code&gt;'a'&lt;/code&gt; twice. What data structure does this sound like? If the word &lt;em&gt;Set&lt;/em&gt; comes to mind, you're right! &lt;a href="https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;We've covered sets on this blog previously&lt;/a&gt;, but to recap, it's a data structure that stores a series of unique values. &lt;/p&gt;

&lt;p&gt;To make a new set, we simply initiate the &lt;code&gt;set&lt;/code&gt; object in Python.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_substrings(word):
  s = set()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we reach the next phase of the implementation. How are we going to add each substring? Let's say we have the string &lt;code&gt;'abc'&lt;/code&gt;. We can start with the first letter, &lt;code&gt;'a'&lt;/code&gt;, and add it to the set. Next, we want to add the letter &lt;code&gt;'b'&lt;/code&gt;, along with &lt;code&gt;'b'&lt;/code&gt; concatenated to everything previously in the set, namely &lt;code&gt;'a'&lt;/code&gt; to make &lt;code&gt;'ab'&lt;/code&gt;.  The two rules in each iteration are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add the new letter. (e.g. &lt;code&gt;'b'&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Add the new letter concatented with every previous substring (e.g. '&lt;code&gt;ab&lt;/code&gt;')&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;However, we can simplify this into one rule. If we add an empty string to the set, we only need #2, since #1 is covered by adding the new letter to an empty string. Altogether, these are the substrings that would be added for each iteration:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Iteration&lt;/th&gt;
&lt;th&gt;Set Before Addition&lt;/th&gt;
&lt;th&gt;Letter to Add&lt;/th&gt;
&lt;th&gt;New Subsets&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;&lt;code&gt;{ '' }&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;a&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;'a'&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;{ '', 'a' }&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;b&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;'b'&lt;/code&gt; &lt;code&gt;'ab'&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;&lt;code&gt;{ '', 'a', 'b', 'ab' }&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;c&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;'c'&lt;/code&gt; &lt;code&gt;'ac'&lt;/code&gt; &lt;code&gt;'bc'&lt;/code&gt; &lt;code&gt;'abc'&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h5&gt;
  
  
  Result: &lt;code&gt;{ '', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc' }&lt;/code&gt;
&lt;/h5&gt;

&lt;p&gt;Let's go about implementing this in code. As we established earlier, we need to start with an empty string in our set. Let's do that.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_substrings(word):
  s = set()
  s.add('')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we need to define our iteration. We want to look at each letter in the string. Simple enough, we use a &lt;code&gt;for&lt;/code&gt; loop. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for letter in word:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Okay, so for each letter in the word, we need to loop through everything in the set and add new combos with that letter. However, if we try to change the set while we're looping through it, we'll get an error. So, we'll have to make a copy of it. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for letter in word:
    new_set = s.copy()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Remember that we have to use the Python &lt;code&gt;.copy()&lt;/code&gt; method, or else we'll just create a reference to the original set. This way, we have an unmodified copy to refer back to.&lt;/p&gt;

&lt;p&gt;Next, we loop through the elements in the immutable copy. For each substring, we want to add the current letter, and then push it onto the set.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for letter in word:
    new_set = s.copy()
    for substr in new_set:
      s.add(substr + letter)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we have our substrings. We just have to do some formatting to get it how the prompt wants it. First of all, we have this extra empty string element in the set. Let's remove that. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  s.remove('')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Simple. Next, as you remember, we want to return a list, not a set. How do we cast something to a list? We iterate over each of its contents and wrap it in some square brackets, like so:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  s = [letter for letter in s]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can just reassign it to &lt;code&gt;s&lt;/code&gt;, since we don't need that variable for anything else. Finally, we want to sort it. Simply call the &lt;code&gt;.sort()&lt;/code&gt; method on our list.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s.sort()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's it, all that's left is to return &lt;code&gt;s&lt;/code&gt;. Altogether:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_substrings(word):&lt;br&gt;
  s = set()&lt;br&gt;
  s.add('')&lt;br&gt;
  for letter in word:&lt;br&gt;
    new_set = s.copy()&lt;br&gt;
    for substr in new_set:&lt;br&gt;
      s.add(substr + letter)&lt;br&gt;
  s.remove('')&lt;br&gt;
  s = [letter for letter in s]&lt;br&gt;
  s.sort()&lt;br&gt;
  return s&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Try it Out&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Call the method &lt;code&gt;find_substrings()&lt;/code&gt; on the string &lt;code&gt;'abc'&lt;/code&gt;, and print the result. We should get: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;['a', 'ab', 'abc', 'ac', 'b', 'bc', 'c']&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Longer words will also work. &lt;code&gt;'abracadabra'&lt;/code&gt; will give us:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;['a', 'aa', 'aaa', 'aaaa', 'aaaaa', 'aaaab'&lt;/code&gt;...&lt;/p&gt;

&lt;p&gt;You get the idea. The point is that &lt;code&gt;'a'&lt;/code&gt; only appears once, and the list is sorted alphabetically.&lt;/p&gt;

&lt;h2&gt;
  
  
  Further Reading: Optimization
&lt;/h2&gt;

&lt;p&gt;This was a conceptually simple solution, and the implementation of more optimal solutions won't be covered in this article. But how might we go about this?&lt;/p&gt;

&lt;p&gt;Instead of using a set, keep the final output as a list, and only insert new strings in a sorted order. Whenever we find a new substring to add to it, we use a &lt;a href="https://dev.to/pythonwb/algorithms-in-python-how-to-implement-binary-search-10d4"&gt;binary search&lt;/a&gt; to figure out where it should be added. If the string already exists in that point, there's no need to add it again. This saves us from the O(N log N) runtime of running &lt;code&gt;sort()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is one of those concepts that appears in different forms in assorted coding challenges. I hope this has added to your coding knowledge toolbox, and you'll be prepared the next time it comes up! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch"&gt;&amp;lt;&amp;lt; Week 15: Binary Trees&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/find_strings.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/help-pierre-the-py-pirate-solve-this-knapsack-problem-7jo"&gt;Week 17: Knapsack &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codenewbie</category>
      <category>beginners</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>(Binary) Christmas Trees! Learn the Three Simplest Tree Traversals in Python
</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Tue, 22 Dec 2020 02:14:47 +0000</pubDate>
      <link>https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch</link>
      <guid>https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;&amp;lt;&amp;lt; Week 14: Random Number&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/unival-tree.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj"&gt;Week 16: Find Substrings &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpreview.redd.it%2Flic4o5dvxn5y.jpg%3Fwidth%3D640%26crop%3Dsmart%26auto%3Dwebp%26s%3Dc72dd64baa46657f696b4404ce74cfc29ce28e26" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpreview.redd.it%2Flic4o5dvxn5y.jpg%3Fwidth%3D640%26crop%3Dsmart%26auto%3Dwebp%26s%3Dc72dd64baa46657f696b4404ce74cfc29ce28e26" alt="christmas tree with 1 and 0s as ornaments"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Someone on r/ProgrammingJokes thought they were really clever. (Image: Reddit)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I've been meaning to cover the topic of binary trees on here for some time, so I thought, why not make it festive? Okay, I know it's not everyone's favorite topic. It's one of those old programming concepts that is hotly debated in the developer community. Since it's rare that you'd actually come across them in industry, it's contested whether or not they should still be fair game in an interview.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fexternal-preview.redd.it%2FuJWHBA6o2sIQXno-sNs1SHHmDPV0DyQuK7ouz0gT0Xs.jpg%3Fauto%3Dwebp%26s%3D4c6dfa15981edace543a22bda0d039aa0a1f9cba" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fexternal-preview.redd.it%2FuJWHBA6o2sIQXno-sNs1SHHmDPV0DyQuK7ouz0gT0Xs.jpg%3Fauto%3Dwebp%26s%3D4c6dfa15981edace543a22bda0d039aa0a1f9cba" alt="Max Howell on Twitter: 'Google: 90% of our engineers use the software you wrote (Homebrew) but you can't invert a binary tree on a whiteboard so f off'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We won't be inverting a binary tree today (*phew*), but we'll look at a couple traversal methods, and you'll find that binary trees aren't too terribly complicated to set up.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Binary Tree, Anyway?
&lt;/h2&gt;

&lt;p&gt;You may remember &lt;a href="https://dev.to/erikhei/what-are-linked-lists-and-how-do-i-make-one-in-python-8ea"&gt;linked lists&lt;/a&gt; from when we covered them in a previous article. Each list is made up of a series of nodes pointing to other nodes. But what if a node could point to more than one node? Trees are exactly that, where each parent node can have multiple children. We call it a binary tree if the max number of children is 2: a left and a right child node. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmedia.geeksforgeeks.org%2Fwp-content%2Fcdn-uploads%2F2009%2F06%2Ftree12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmedia.geeksforgeeks.org%2Fwp-content%2Fcdn-uploads%2F2009%2F06%2Ftree12.gif" alt="binary tree"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: GeeksForGeeks)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the above example, the "root", meaning the topmost node, has a value of 1, and its children are the nodes 2 and 3, and so on. Nodes 3, 4, and 5 might be referred to as "leaves" because they have no child nodes. &lt;/p&gt;

&lt;p&gt;How would we go about building a tree in Python? It will look similar to our linked list Node class. We'll call it &lt;code&gt;TreeNode&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TreeNode:
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, let's define the &lt;code&gt;__init__()&lt;/code&gt; method. As always, it takes in &lt;code&gt;self&lt;/code&gt;, and we'll also pass in the value to be stored on the node.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TreeNode:
  def __init__(self, value):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We'll set the value of the node, and then we'll define a left and right pointer, which we'll set as &lt;code&gt;None&lt;/code&gt; to start.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TreeNode:
  def __init__(self, value):
    self.value = value
    self.left = None
    self.right = None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And...that's it! What, did you think a tree would be more complicated? For a binary tree, the only difference from a linked list is that instead of &lt;code&gt;next&lt;/code&gt;, we have &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Let's build the tree from the diagram earlier. The top node has a value of 1, and then we just keep setting its left and right nodes until we have the tree we want. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(3)
tree.left.left = TreeNode(4)
tree.left.right = TreeNode(5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Traversing the Tree
&lt;/h2&gt;

&lt;p&gt;So you've built the tree, and now you're asking, "How do I see the tree I just built?" You can't just print the whole tree in one command, but we can traverse over each node. But what in what order should we print each node?&lt;/p&gt;

&lt;p&gt;The three easiest traversals to implement are &lt;strong&gt;Pre-Order&lt;/strong&gt;, &lt;strong&gt;Post-Order&lt;/strong&gt;, and &lt;strong&gt;In-Order&lt;/strong&gt;. You'll also hear the terms breadth-first and depth-first search, but the implementation of these is more complicated, so we'll cover them in a future article. So what are the three listed above? Let's look at our tree again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmedia.geeksforgeeks.org%2Fwp-content%2Fcdn-uploads%2F2009%2F06%2Ftree12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmedia.geeksforgeeks.org%2Fwp-content%2Fcdn-uploads%2F2009%2F06%2Ftree12.gif" alt="binary tree"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: GeeksForGeeks)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pre-Order&lt;/strong&gt; visits a parent node before its children. Pre-order of the above tree would result 1, 2, 4, 5, 3.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Post-Order&lt;/strong&gt; visits a node's children first, and then the parent. Post-order would result in 4, 5, 2, 3, 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In-Order&lt;/strong&gt; visits each node from left to right. In-order traversal of the the above tree would give us 4, 2, 5, 1, 3&lt;/p&gt;

&lt;p&gt;Let's write the traversal methods for our binary tree. Start by defining the &lt;code&gt;pre_order()&lt;/code&gt; method, which can go outside the &lt;code&gt;TreeNode&lt;/code&gt; class. Our method takes one argument, the highest parent, a.k.a. the root node. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def pre_order(node):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we want to check that the node exists. You could argue that we could instead check if its children exist before visiting them, but we would have to write two &lt;code&gt;if&lt;/code&gt; statements, and this way we only need to write one.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def pre_order(node):
  if node:
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To write the traversal is simple. Pre-order visits the parent and then each child, so we're going to "visit" the parent by printing it, and then "traverse" to the children by calling the method recursively on each child.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# prints the parent before each child
def pre_order(node):
  if node:
    print(node.value)
    pre_order(node.left)
    pre_order(node.right)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Simple, right? You can test it out with the tree we built earlier.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pre_order(tree)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And the results:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
2
4
5
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Excellent. Next, let's do post-order. You may think that we have to write a whole new method, but actually, we just need to change one line. Instead of "visiting" the node and then "traversing" the children, we just "traverse" the children first, and then "visit" the parent node. What do I mean by this? Simply move the print statement to the last line! Remember to change the name of all your function calls to &lt;code&gt;post_order()&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# prints children and then parent
def post_order(node):
  if node:
    post_order(node.left)
    post_order(node.right)
    print(node.value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Printing the result should give us the following: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;4
5
2
3
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Where each child node is visited before its parent. &lt;/p&gt;

&lt;p&gt;Last, we need to write the In-Order traversal. How do you traverse the left node, and then visit the parent, and then traverse the right? Again, we just move the print statement! &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# prints left child, parent, then right child
def in_order(node):
  if node:
    in_order(node.left)
    print(node.value)
    in_order(node.right)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if we print the tree, the nodes are printed "in order."&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;4
2
5
1
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And there you have it, the three simplest ways to traverse a binary tree. Have a happy holiday, however you celebrate (socially distanced of course). I hope this helped you learn more about the binary trees!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;&amp;lt;&amp;lt; Week 14: Random Number&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/trees-and-graphs/unival-tree.py" rel="noopener noreferrer"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-strings-can-you-solve-this-more-difficult-string-problem-2lfj"&gt;Week 16: Find Substrings &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>computerscience</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
    <item>
      <title>More Python Practice: Find the Random Number (ft. Sets!)</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Thu, 17 Dec 2020 19:13:09 +0000</pubDate>
      <link>https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf</link>
      <guid>https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p"&gt;&amp;lt;&amp;lt; Week 13: Diving Board&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/random_num.py" rel="noopener noreferrer"&gt;View Solution on Github&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch"&gt;Week 15: Binary Trees &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.fastcompany.net%2Fimage%2Fupload%2Fw_596%2Cc_limit%2Cq_auto%3Abest%2Cf_auto%2Fwp-cms%2Fuploads%2Fsites%2F4%2F2017%2F08%2Fi-2-this-security-firms-office-design-adds-to-the-strength-of-its-encryption.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.fastcompany.net%2Fimage%2Fupload%2Fw_596%2Cc_limit%2Cq_auto%3Abest%2Cf_auto%2Fwp-cms%2Fuploads%2Fsites%2F4%2F2017%2F08%2Fi-2-this-security-firms-office-design-adds-to-the-strength-of-its-encryption.gif" alt="Wall of lava lamps"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cloudflare in San Francisco uses &lt;a href="https://www.fastcompany.com/90137157/the-hardest-working-office-design-in-america-encrypts-your-data-with-lava-lamps" rel="noopener noreferrer"&gt;lava lamps&lt;/a&gt; as a random number generator to encrypt requests (Source: Fast Company)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Random numbers, the spice of life. Or, at least in the coding world, they are. The &lt;a href="https://www.boredapi.com/" rel="noopener noreferrer"&gt;Bored API&lt;/a&gt; uses random numbers to find an activity to alleviate your boredom, and games like Minecraft use them to spawn random terrain (check out my simple 2D Javascript Minecraft spin-off &lt;a href="https://erik-hei.github.io/frogcraft/" rel="noopener noreferrer"&gt;here&lt;/a&gt;). And there are more practical uses, like encryption at CloudFlare, which uses a &lt;a href="https://www.fastcompany.com/90137157/the-hardest-working-office-design-in-america-encrypts-your-data-with-lava-lamps" rel="noopener noreferrer"&gt;wall of lava lamps&lt;/a&gt; as a random number generator to encrypt web requests. &lt;/p&gt;

&lt;p&gt;So let's talk about using random numbers in Python. Here is a sample interview question.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Given an integer n and a list of integers, 
# write a function that randomly generates a number 
# from 0 to n-1 that isn't in the list.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There are two things we'll need if we're going to generate a random integer. One is the Python &lt;code&gt;random&lt;/code&gt; library, and we'll also need the &lt;code&gt;math&lt;/code&gt; library to round down our random number to an integer. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random
import math
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, as always, we define our method. It takes in a number and a list of integers, which we'll call &lt;code&gt;nums&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_rand(n, nums):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Solution 1: Reroll
&lt;/h2&gt;

&lt;p&gt;Let's talk strategy. The first one we'll discuss is a "galaxy brain" sort of idea that perhaps first comes to mind: find a random number in the given range, and then if it's in the list, simply run the random number generator again until we find one that's valid.&lt;/p&gt;

&lt;p&gt;We'll start by getting a random number between 0 and n. The &lt;code&gt;random&lt;/code&gt; object has a method called &lt;code&gt;random()&lt;/code&gt; which returns a random (decimal) number between 0 and 1. To get a numbet between 0 and n, we multiply it by n, and then we round down using &lt;code&gt;math.floor()&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  rand_num = math.floor(random.random() * n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You might start by getting the random number, but there's something else we can use to make the (pretty terrible) runtime a bit better. Let's look at something used in many programming languages called a set.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Set&lt;/em&gt; - A data type that stores unique values in no particular order.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Frzmfwazi2ugmx71l5mi9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Frzmfwazi2ugmx71l5mi9.png" alt="cloud of numbers"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A visualization of the Set datatype.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I like to think of sets as a cloud: a bunch of numbers floating around, but there's no order to them. What's important is that no number appears twice. If you try to add 3 to a set, and it's already in there, it won't get added again. What's useful for us is that checking to see if the set contains a certain number takes constant O(1) time. This is better than the O(N) time we'd get if we had to loop through a list every time.&lt;/p&gt;

&lt;p&gt;How do we implement a set in Python? Start by calling the set class with its constructor, &lt;code&gt;set()&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  s = set()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we add the numbers from the list into the set. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for num in nums:
    s.add(num)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we check to see if the random number we made is in the set. If not, we want to find a new random number. This can be achieved with a &lt;code&gt;while&lt;/code&gt; loop that runs if the random number is in the set. For fun, you can put a print statement to see how many times the method has to find a new number before it finds one that is valid. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  while rand_num in s:
    print("reroll")
    rand_num = math.floor(random.random()*n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And finally, we return the resulting random number once the &lt;code&gt;while&lt;/code&gt; loop has been exited. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_rand(n, nums):
  rand_num = math.floor(random.random()*n)
  s = set()
  for num in nums:
    s.add(num)
  while rand_num in s:
    print("reroll")
    rand_num = math.floor(random.random()*n)
  return rand_num
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we try it out by printing &lt;code&gt;get_rand(5, [0, 1, 2, 3])&lt;/code&gt;, we should get 4, which is the only number left that is less than 5, and that isn't in the list. &lt;/p&gt;

&lt;p&gt;As I mentioned earlier, the runtime for this solution is not terribly efficient. Potentially, the algorithm could keep picking random numbers into eternity if it doesn't find the right one--which is exactly what happens if there &lt;em&gt;are&lt;/em&gt; no numbers that meet the criteria. Why don't you try printing the result of &lt;code&gt;get_rand(5, [0, 1, 2, 3, 4])&lt;/code&gt;, where the list contains all the numbers that are less than 5. Does it look like this?&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reroll
reroll
reroll  
reroll
reroll
reroll
reroll
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The algorithm keeps rerolling to eternity since there are no possible numbers to choose from. Let's think of a different solution that will both address this edge case and eliminate infinite runtime.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution 2: List of Possible Numbers
&lt;/h2&gt;

&lt;p&gt;Sometimes, we approach these programming questions as though we're solving a math program, and we forget: we're &lt;em&gt;developers&lt;/em&gt;. We &lt;em&gt;build things&lt;/em&gt;. So one approach is to always ask, "Can I build the thing I need to solve this problem?"&lt;/p&gt;

&lt;p&gt;Imagine instead of having to check each time if our random number was in the list, we already had of list of valid numbers to choose from. Then, we would just pick a random number in the list. This would also solve our edge case, because we would know that this list of possible numbers is empty, we should return None.&lt;/p&gt;

&lt;p&gt;The first part of our method will remain the same: we take the numbers from the &lt;code&gt;nums&lt;/code&gt; list and put them in a set. Then, we want to make an empty list that will contain all the possible numbers to choose from.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_rand2(n, nums):
  s = set()
  for num in nums:
    s.add(num)
  poss_nums = []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;How do we find the valid numbers? We simply loop through every integer from 0 to &lt;code&gt;n&lt;/code&gt;, and if it's not in the set, we add it to the list. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for num in range(n):
    if num not in s:
      poss_nums.append(num)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we were to run our call from earlier, &lt;code&gt;get_rand(5, [0, 1, 2, 3])&lt;/code&gt;, we would get a list of &lt;code&gt;poss_nums&lt;/code&gt; containing only the number 4. &lt;/p&gt;

&lt;p&gt;Next, we check for our edge case. Simply check if the list is empty, and if so, return &lt;code&gt;None&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  if not len(poss_nums):
    return None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's left? To pick our random number, of course! Using the &lt;code&gt;random.random()&lt;/code&gt; function, we multiply it by the length of the list to  pick a random index, and then we'll return the number at that index. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  rand_i = math.floor(random.random()*len(poss_nums))
  return poss_nums[rand_i]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it! The method looks like this in total:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_rand2(n, nums):
  s = set()
  for num in nums:
    s.add(num)
  poss_nums = []
  for num in range(n):
    if num not in s:
      poss_nums.append(num)
  if not len(poss_nums):
    return None
  rand_i = math.floor(random.random()*len(poss_nums))
  return poss_nums[rand_i]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, if we try running &lt;code&gt;get_rand(5, [0, 1, 2, 3, 4])&lt;/code&gt; and print the result, we should get None because there are no numbers that meet the criteria. Hooray! No more infinite loops. &lt;/p&gt;

&lt;p&gt;That's all for this week. If you like this content, please let me know in the comments what you would like to see next!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p"&gt;&amp;lt;&amp;lt; Week 13: Diving Board&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/arrays-and-strings/random_num.py" rel="noopener noreferrer"&gt;View Solution on Github&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/binary-christmas-trees-learn-the-three-simplest-tree-traversals-in-python-41ch"&gt;Week 15: Binary Trees &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codenewbie</category>
      <category>computerscience</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Dive into Python with this Diving Board Problem (ft. Recursion)!</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Mon, 07 Dec 2020 22:11:45 +0000</pubDate>
      <link>https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p</link>
      <guid>https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig"&gt;&amp;lt;&amp;lt; Week 12: Robot&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/recursion/add_to_k.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;Week 14: Random Number &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gCkWrSiH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.mandatory.com/assets/uploads/gallery/poolside-gifs/giphy-3.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gCkWrSiH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.mandatory.com/assets/uploads/gallery/poolside-gifs/giphy-3.gif" alt="corgi diving into a pool"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Like a pro. (Image: Mandatory.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I'm going to say one word: Recursion. What is your initial reaction? Fear? Excitement? Back in my CS days at uni, they made sure to take caution introducing this subject: &lt;em&gt;"It's so unintuitive!"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In all honesty, though, recursion is just another way to solve iterative problems. We got our &lt;code&gt;for&lt;/code&gt; loops, for 10 times do X. But in recursion, &lt;em&gt;X&lt;/em&gt; is to call the same method again. And instead of calling it 10 times, we call it until the conditions are met. What are the conditions? That's for us to determine. Let's look at this sample interview question.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# A diving board must be built to a certain length,
# made up only of the given pieces of wood

# Given a list of numbers (the lengths of wood)
# and a number k, return whether any two numbers 
# from the list add up to k.

# For example, given [10, 15, 3, 7] and k of 17, return 
# True, since 10 + 7 is 17.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;First, let's take a step back and think how we might solve this iteratively. A "brute force" solution, if you will. We'll simply create a nested &lt;code&gt;for&lt;/code&gt; loop where we check every single number against every other number in the list to see if they add to &lt;code&gt;k&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Start with a method &lt;code&gt;add_to_k()&lt;/code&gt; that takes in two parameters, our &lt;code&gt;numbers&lt;/code&gt; list, and the sum &lt;code&gt;k&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k(numbers, k):
  pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Our first &lt;code&gt;for&lt;/code&gt; loop will run up through the end of the list minus 1, since by the time we get to the last element, there's nothing behind it to compare it with.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k(numbers, k):
  for i in range(len(numbers) - 1):
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We'll keep track of the first number we find and call it &lt;code&gt;current&lt;/code&gt;. Next, we want to look at all the numbers in the list behind it. This can be achieved with the nested &lt;code&gt;for&lt;/code&gt; loop as shown.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k(numbers, k):
  for i in range(len(numbers) - 1):
    current = numbers[i]
    for j in range(i + 1, len(numbers)):
        ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, if the sum of the two numbers is equal to &lt;code&gt;k&lt;/code&gt;, we return True. If we loop through the entire list without finding a match, we return False. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k(numbers, k):
  for i in range(len(numbers) - 1):
    current = numbers[i]
    for j in range(i + 1, len(numbers)):
      # print("checking", current, "+", numbers[j])
      if current + numbers[j] == k:
        return True
  return False  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's try running the solution. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num_list = [10, 15, 3, 7]
k = 10

print(add_to_k(num_list, k))
# -&amp;gt; True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Great. This solution does the trick, but how would we go about solving it recursively? &lt;/p&gt;

&lt;h2&gt;
  
  
  Writing the Recursive Solution
&lt;/h2&gt;

&lt;p&gt;The method will start the same, taking in the same &lt;code&gt;numbers&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; parameters as before.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k_recursive(numbers, k):
  pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, we need to determine our base case(s). With recursion, the best thing to ask is, "What is the simplest case?" Put on your lazy engineer hat; if you had to solve this problem looking at a bunch of different lists, which one would you want to solve? Perhaps a list that only has one item, in which case, the answer must always be false. This is our primary base case. I'm making the length less than 2, since an empty list would also fall into this category.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k_recursive(numbers, k):
  if (len(numbers) &amp;lt; 2):
    return False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What's next? We have one more base case to write. If a list must be at least 2 long, the easiest case would be...if the list were only 2 long! Then we would simply add the two numbers and see if they equal &lt;code&gt;k&lt;/code&gt;. In the case that we don't know the length of the list, let's default to checking the first and last number. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k_recursive(numbers, k):
  if (len(numbers) &amp;lt; 2):
    return False
  elif numbers[0] + numbers[-1] == k:
    return True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now all we have to do is make our recursive case, i.e., the one where we call our method again. &lt;/p&gt;

&lt;p&gt;Let's think about it. Our list is &lt;code&gt;[10, 15, 3, 7]&lt;/code&gt;, and we're looking for numbers that sum to 10. Obviously, the length is longer than 2, so we skip the first &lt;code&gt;if&lt;/code&gt; statement. In the &lt;code&gt;elif&lt;/code&gt;, we see that the first and last numbers, 10 and 7, add to 17, which is not 10. So now what?&lt;/p&gt;

&lt;p&gt;We'll have to call &lt;code&gt;add_to_k_recursive()&lt;/code&gt; on a smaller list so that the first and last numbers are different. There are two lists we can check:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Everything but the first value.&lt;/li&gt;
&lt;li&gt;Everything but the last value.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These are, in python:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers[1:]
numbers[:-1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So, we'll call our method twice, once for each of the two smaller lists. What do we return? Remember that in Python, &lt;code&gt;or&lt;/code&gt; will return the first True value. So, we return one method call or the other.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_k_recursive(numbers, k):
  if (len(numbers) &amp;lt; 2):
    return False
  elif numbers[0] + numbers[-1] == k:
    return True
  else:
    return add_to_k_recursive(numbers[:-1], k) or add_to_k_recursive(numbers[1:], k)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Testing it Out
&lt;/h2&gt;

&lt;p&gt;Running the same code as before should give us the same output of True.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num_list = [10, 15, 3, 7]
k = 10

print(add_to_k_recursive(num_list, k))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;However, let's look at what's going on under the hood.&lt;/p&gt;

&lt;p&gt;We start with the list &lt;code&gt;[10, 15, 3, 7]&lt;/code&gt;. As stated before, the first and last numbers don't add to 10. So, we call the function again on the smaller lists, &lt;code&gt;[10, 15, 3]&lt;/code&gt; and &lt;code&gt;[15, 3, 7]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Each of those lists will get broken down again, so the second list will get split into &lt;code&gt;[15, 3]&lt;/code&gt; and &lt;code&gt;[3, 7]&lt;/code&gt;, the last one returning True. So, True gets returned up the chain of command through the initial instance of our method.&lt;/p&gt;

&lt;p&gt;I hope this helped clear up your understanding of recursion. We didn't make the run time any better, since we still have to look at every number about two times, or O(N&lt;sup&gt;2&lt;/sup&gt;) complexity. However, you might look at this solution and find it more elegant. Regardless, recursion is a good trick to have in your bag, especially if you see the words "check all possible combinations" looming in an interview question. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig"&gt;&amp;lt;&amp;lt; Week 12: Robot&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/recursion/add_to_k.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/more-python-practice-find-the-random-number-ft-sets-50lf"&gt;Week 14: Random Number &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codenewbie</category>
      <category>beginners</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Robot Vacuum in Python: Bring Him Home!
</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Wed, 02 Dec 2020 00:33:20 +0000</pubDate>
      <link>https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig</link>
      <guid>https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/merge-sort-when-you-re-too-much-of-a-nerd-to-use-sort-34ki"&gt;&amp;lt;&amp;lt; Week 11: Merge Sort&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/robot_return_home.py"&gt;View Solution on Github&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p"&gt;Week 13: Diving Board &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/hO0X9iUHoCpvG/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/hO0X9iUHoCpvG/giphy.gif" alt="cat on roomba"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;My ride is here. (Image: Catcheckup.com)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I'm sure you remember when Roombas first came out, and how they were all the rage. Where are they now? Is our humble explorer still roaming the endless carpet of a &lt;a href="https://mcmansionhell.com/post/628714198070902784/the-mcmansion-hell-yearbook-1976"&gt;McMansion bedroom suite&lt;/a&gt; that it hasn't left since 2007? &lt;/p&gt;

&lt;p&gt;This sample interview question has to do with exactly that. Let's take a look.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Given a string representing the sequence of moves a 
# robot vacuum makes, return whether or not it will 
# return to its original position. 
#
# The string will only contain L, R, U, and D characters, 
# representing left, right, up, and down respectively. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Does it sound complicated? Don't worry, we're going to break it down step by step.&lt;/p&gt;

&lt;p&gt;Let's start with defining the method. It takes in one parameter, a string which we'll call &lt;code&gt;direction&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def return_home(directions):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, you might have guessed it--some math is involved. Let's think back to primary school and the cartesian coordinate system. Our humble robot explorer starts at the origin and travels a few directions, say one foot right and two up. It would be at the position (1, 2). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--E3L0_HQ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1szv4o57x55cg4qg15lc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--E3L0_HQ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1szv4o57x55cg4qg15lc.png" alt="graph to 1,2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How would we move it back home? We would move it two feet down in the minus Y-direction and one left, in the minus X-direction. But it doesn't matter which of those actions we take first. As long as we move -1 X and -2 Y, our humble robot explorer will return to its home at (0, 0). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dPkYfB-z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2wz9j38k01uc74qrcc9b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dPkYfB-z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2wz9j38k01uc74qrcc9b.png" alt="graph back to 0,0 "&gt;&lt;/a&gt;&lt;br&gt;
So, we can keep track of the robot's X and Y coordinates, adding or subtracting 1 based on each direction we get, and if by the end of the &lt;code&gt;directions&lt;/code&gt; string, we have an X and Y coordinate of (0, 0), the robot has returned home. Hooray!&lt;/p&gt;

&lt;p&gt;The first thing we'll do is define those x and y coordinates. They both start at 0. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def return_home(directions):
  x = 0
  y = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we want to iterate over each letter in the string. A &lt;code&gt;for&lt;/code&gt; loop should work. I'm calling each letter a &lt;code&gt;direction&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for direction in directions:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, let's make a simple &lt;code&gt;if&lt;/code&gt; statement for each one. We've established that "R" (right) is in the positive X-direction, and "L" (left) is the negative X-direction, so we'll add or subtract 1 to &lt;code&gt;x&lt;/code&gt; accordingly.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for direction in directions:
    if direction == "R":
      x += 1
    elif direction == "L":
      x -= 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The Y-direction is fairly the same, we add 1 for "U" (up), and subtract 1 for "D" (down).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for direction in directions:
    if direction == "R":
      x += 1
    elif direction == "L":
      x -= 1
    elif direction == "U":
      y += 1
    elif direction == "D":
      y -= 1    
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once we have looped through each direction in the string, we're ready to check if our robot has returned home. Simply return whether or not &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; are equal to zero. Be sure that this goes outside the &lt;code&gt;for&lt;/code&gt; loop. Altogether:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def return_home(directions):
  x = 0
  y = 0
  for direction in directions:
    if direction == "R":
      x += 1
    elif direction == "L":
      x -= 1
    elif direction == "U":
      y += 1
    elif direction == "D":
      y -= 1
  return x == 0 and y == 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Testing it out
&lt;/h2&gt;

&lt;p&gt;Let's try the example from earlier, one right and two up. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(return_home("RUU"))
# -&amp;gt; False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But, if we go two down and one left, we should get &lt;code&gt;True&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(return_home("RUULDD")
# -&amp;gt; True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can try out an impressively long string of letters to see if the robot can make it back from the other side of the McMansion lawyer foyer.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(return_home("LRULLRRDDRUDLLLURRLRULLRRDDRUDLLLURR"))
# -&amp;gt; True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it for this week, please follow the blog if you're interested in more Python practice. Also, I would like to hear from you! Let me know in the comments if there are any topics you'd like us to cover.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/merge-sort-when-you-re-too-much-of-a-nerd-to-use-sort-34ki"&gt;&amp;lt;&amp;lt; Week 11: Merge Sort&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/misc/robot_return_home.py"&gt;View Solution on Github&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/dive-into-python-with-this-diving-board-problem-ft-recursion-453p"&gt;Week 13: Diving Board &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>computerscience</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Merge Sort: When You're Too Much of a Nerd to Use .sort()</title>
      <dc:creator>Whiteboarding in Python</dc:creator>
      <pubDate>Mon, 23 Nov 2020 20:24:45 +0000</pubDate>
      <link>https://dev.to/pythonwb/merge-sort-when-you-re-too-much-of-a-nerd-to-use-sort-34ki</link>
      <guid>https://dev.to/pythonwb/merge-sort-when-you-re-too-much-of-a-nerd-to-use-sort-34ki</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/pythonwb/back-to-basics-more-strings-in-python-3cn1"&gt;&amp;lt;&amp;lt; Week 10: Urlify&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/search-and-sort/merge_sort.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig"&gt;Week 12: Robot Vacuum &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It's the age old question. &lt;em&gt;"I have a list of things and I want to sort them. What do?"&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wklOmn_4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://ichef.bbci.co.uk/news/800/cpsprodpb/92F3/production/_114391673_gettyimages-1158923430.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wklOmn_4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://ichef.bbci.co.uk/news/800/cpsprodpb/92F3/production/_114391673_gettyimages-1158923430.jpg" alt="bunch of legos"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image: BBC)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Well, clearly, the most intuitive answer is to take the list, divide it in half, and in half and in half until you have a bunch of lists 1 length long, and then put each pair back together in the right order, and then put the little sorted pairs together in bigger sorted pairs, and then again until you have a full list, but sorted. Is that what you were thinking? &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2BXfoIeA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Merge_sort_algorithm_diagram.svg/600px-Merge_sort_algorithm_diagram.svg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2BXfoIeA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Merge_sort_algorithm_diagram.svg/600px-Merge_sort_algorithm_diagram.svg.png" alt="merge sort diagram"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Looks something like this. (Source: Wikipedia)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Okay, so maybe it's not the most intuitive solution, but I'll spare you the tedious hand holding of walking through inferior search algorithms like bubble sort and bogo sort (*shudder*) before explaining merge sort. What you need to know is that merge sort has a pretty good runtime compared to other algorithms, which, as you may have guessed from the whole "split in half" thing, is O(N log N). &lt;/p&gt;

&lt;p&gt;Let's get started. Make the &lt;code&gt;merge_sort()&lt;/code&gt;, which takes in a list. We'll call it &lt;code&gt;nums&lt;/code&gt; for our purposes, but this same method would work for a list of any sortable types, such as strings. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def merge_sort(nums):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The first step is to divide the list in half. Use integer division to make sure we get a whole number index (in case the list is odd). Then we'll make two smaller lists, &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt;, using python's handy sub-list notation. Wait, what if the list is 0 or 1 long? Then we can't split it in half. This is why we wrap our entire method in an if statement, ensuring it only operates if the list is greater than 1.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def merge_sort(nums): 
  if len(nums) &amp;gt;1: 
    mid = len(nums)//2
    left = nums[:mid] 
    right = nums[mid:]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What do we do next? Simple! Sort the two halves by calling &lt;code&gt;merge_sort()&lt;/code&gt; on them. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def merge_sort(nums): 
  if len(nums) &amp;gt;1: 
    mid = len(nums)//2
    left = nums[:mid] 
    right = nums[mid:]
    merge_sort(left) 
    merge_sort(right) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But wait, we're not done. So far, we've split the list into halves repeatedly until we have a bunch of little lists length one. For example, if we had the list &lt;code&gt;[4, 2, 1, 3]&lt;/code&gt;, it would get split into &lt;code&gt;[4, 2]&lt;/code&gt; and &lt;code&gt;[1, 3]&lt;/code&gt;, and then into &lt;code&gt;[4]&lt;/code&gt;, &lt;code&gt;[2]&lt;/code&gt;, &lt;code&gt;[1]&lt;/code&gt;, and &lt;code&gt;[3]&lt;/code&gt;, lists each of length 1. &lt;/p&gt;

&lt;p&gt;What's next? I'll give you a hint, it's in the name of the method...rhymes with blurge....right! We merge the halves together. &lt;/p&gt;

&lt;p&gt;Things get a little tricky here. We need to keep track of a few indices, which we'll call &lt;code&gt;i&lt;/code&gt;, &lt;code&gt;j&lt;/code&gt;, and &lt;code&gt;k&lt;/code&gt;. Here is what they represent:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;i&lt;/code&gt; is an index in the &lt;code&gt;left&lt;/code&gt; list.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;j&lt;/code&gt; is an index in the &lt;code&gt;right&lt;/code&gt; list.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;k&lt;/code&gt; is the index in the original list, &lt;code&gt;nums&lt;/code&gt; where we want to put each number when we're done.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To start, we'll make all of them zero.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = j = k = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, we're going to traverse both the left and right lists, comparing each item. We only need to go through once because &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; are already sorted. We just need to merge them. &lt;/p&gt;

&lt;p&gt;If the number in &lt;code&gt;left&lt;/code&gt; is smaller, we put it back in &lt;code&gt;nums&lt;/code&gt; at spot &lt;code&gt;k&lt;/code&gt;, and advance our left index &lt;code&gt;j&lt;/code&gt;. If the number in &lt;code&gt;right&lt;/code&gt; is smaller (or equal), we put it in &lt;code&gt;nums&lt;/code&gt; instead, and advance our right index, &lt;code&gt;j&lt;/code&gt;. Finally, we advance &lt;code&gt;k&lt;/code&gt; now that we have added a new number to &lt;code&gt;nums&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while i &amp;lt; len(left) and j &amp;lt; len(right): 
    if left[i] &amp;lt; right[j]: 
        nums[k] = left[i] 
        i+=1
    else: 
        nums[k] = right[j] 
        j+=1
    k+=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There's one more thing we need to do. We said &lt;code&gt;while i &amp;lt; len(left) and j &amp;lt; len(right)&lt;/code&gt;, meaning as soon as one of those conditions is met, the loop will break. So let's say we reached the end of &lt;code&gt;left&lt;/code&gt;, but we still have more indices to go in &lt;code&gt;right&lt;/code&gt;? We just have to make another while loop that accounts for this, looping through the rest of &lt;code&gt;right&lt;/code&gt; and adding its numbers into the &lt;code&gt;nums&lt;/code&gt; list. We do the same for any numbers left in &lt;code&gt;left&lt;/code&gt; (ha, left, get it? I'll stop now). &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while j &amp;lt; len(right): 
    nums[k] = right[j] 
    j+=1
    k+=1

while i &amp;lt; len(left): 
    nums[k] = left[i] 
    i+=1
    k+=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it! To recap the merge, we started with &lt;code&gt;[4]&lt;/code&gt;, &lt;code&gt;[2]&lt;/code&gt;, &lt;code&gt;[1]&lt;/code&gt;, and &lt;code&gt;[3]&lt;/code&gt;. These get merged to &lt;code&gt;[2, 4]&lt;/code&gt; and &lt;code&gt;[1, 3]&lt;/code&gt;, and then finally they come together to make &lt;code&gt;[1, 2, 3, 4]&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Here is the full code. Notice that the bulk of the method lies within that first &lt;code&gt;if&lt;/code&gt; statement.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def merge_sort(nums): 
  if len(nums) &amp;gt; 1: 
    mid = len(nums)//2
    left = nums[:mid] 
    right = nums[mid:]
    merge_sort(left) 
    merge_sort(right) 

    i = j = k = 0

    while i &amp;lt; len(left) and j &amp;lt; len(right): 
        if left[i] &amp;lt; right[j]: 
            nums[k] = left[i] 
            i+=1
        else: 
            nums[k] = right[j] 
            j+=1
        k+=1

    while i &amp;lt; len(left): 
        nums[k] = left[i] 
        i+=1
        k+=1

    while j &amp;lt; len(right): 
        nums[k] = right[j] 
        j+=1
        k+=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Testing it out
&lt;/h2&gt;

&lt;p&gt;Let's sort some numbers. Make a list of numbers, and call &lt;code&gt;merge_sort()&lt;/code&gt; on them. Notice how we print the result &lt;em&gt;after&lt;/em&gt; the method call, since it alters the original list &lt;code&gt;nums&lt;/code&gt; instead of returning anything.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nums = [5, 2, 3, 6, 84, 9, 8]
merge_sort(nums)
print(nums)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This should give you the sorted list, &lt;code&gt;[2, 3, 5, 6, 8, 9, 84]&lt;/code&gt;. As mentioned before, this will also work with strings. Giving the list &lt;code&gt;['banana', 'apple', 'grape', 'orange']&lt;/code&gt; will sort alphabetically to &lt;code&gt;['apple', 'banana', 'grape', 'orange']&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I hope this gave you some clarity on how merge sort works. Python's &lt;code&gt;.sort()&lt;/code&gt; method is similar to merge sort and is another "divide and conquer" algorithm, and has about the same time complexity. So, there's not really a reason you would have to implement merge sort...unless you're asked to do so on an technical interview. I hope this helped to prepare you for that!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/pythonwb/back-to-basics-more-strings-in-python-3cn1"&gt;&amp;lt;&amp;lt; Week 10: Urlify&lt;/a&gt; | &lt;a href="https://github.com/sheamus-hei/whiteboarding/blob/master/search-and-sort/merge_sort.py"&gt;View Solution on GitHub&lt;/a&gt; | &lt;a href="https://dev.to/pythonwb/robot-vacuum-in-python-bring-him-home-2gig"&gt;Week 12: Robot Vacuum &amp;gt;&amp;gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sheamus Heikkila is formerly a Teaching Assistant at General Assembly. This blog is not associated with GA.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>computerscience</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
