Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

From a Written Problem to Pseudo Code to Working Code (Python)

blog/cards/from-a-written-problem-to-pseudo-code-to-working-code-python.jpg

You can use this workflow to help convert feature requests, user stories and vague ideas into fully working code.

Quick Jump: The Problem | Busting Out the Pseudo Code | Converting the Above into Python Code | Takeaways | Live Coding Video

Prefer video? There’s a video version of this blog post on YouTube that goes into a bit more detail about certain topics listed below.

In your day to day as a developer you’ll often be asked to convert a written or verbally explained problem into code. This could be anything from a couple of sentences with little direction to a fully mapped out user story.

This may come from someone offering you contract work, a team lead, product owner or even your own mind if you’re working on your own app. Basically this applies to solo developers, contract workers and full time employees.

The Problem

Recently someone emailed me asking to help them write a bit of Python. All I did here was clean up the grammar a tiny bit but I tried to leave things mostly how it was sent to keep it more relatable to how you might encounter written problems in the real world:

Hi, here’s the situation I have a website example.com.

At the moment I want to contact this site and get back specific information, such as example.com/settings/all-server/status.

It shows unformatted information. I’m trying to make a script to find a specific word in the text and store it into a variable.

This is the information (I changed some fields for security reasons):

[{"lastUpdated":0,"id":"123","protocol":"https","hostName":"ipdatas","port":"000","serverName":"training-1-t","status":"online","serverType":"transparency","enabled":true},{"lastUpdated":0,"id":"456","protocol":"https","hostName":"urldatas","port":"000","serverName":"graphql","status":"disconnected","serverType":"quapi","enabled":false},{"lastUpdated":0,"id":"789","protocol":"https","hostName":"ipdatas","port":"000","serverName":null,"status":"online","serverType":"directive","enabled":true}]

In one of the lines there is a word called “TRANSPARENCY” but this doesn’t always appear in the same order for all of the sites.

What I’m trying to achieve here is to be able to detect that word in the line, go to the field “id” and copy that field.

I’ve been trying for a week, do you think you can help?

I replied back to them with “What did you try so far?”.

By the way if you have video topic ideas or problems that seem like a good match for a ~5-30min coding video let me know.

They replied back with:

I tried the library BeautifulSoup, and I printed all the fields. After that I was able to split them, for example deleting the use of commas or any other symbols but nevertheless I have to assign the index number of the TRANSPARENCY word.

What I’m trying to do is be able to return a certain amount of characters until the ID, then copy that single ID and store it in a variable.

I replied back mentioning that the response from the site looks like JSON which is structured text and asked if they tried parsing it that way.

They said they didn’t know how to accomplish that and asked if I knew how.

Busting Out the Pseudo Code

I still don’t know much about the situation and I don’t want to just answer questions for folks in case it’s for a homework assignment or a take home test.

So I replied with:

The steps I would take are:

Parse the site response as JSON
Loop over that response (it's a list)
  If the item's serverType is "transparency"
    Store the item's id or do whatever you need (append this whole item to a new variable, etc.)

My thought process here is I was hoping they would read these steps and see that there is a path forward by breaking down the problem into bite size chunks and then solve them one at a time.

But, they messaged me back asking for a code example because they didn’t have enough Python experience to write the code themselves.

Then I asked them what it’s for and they said a personal project that they might use at work if they’re able to do it. I figured I would help in that case since it’s a few lines of code so I wrote the code out in an email.

Converting the Above into Python Code

I came up with this. I’ve added comments for each pseudo code sentence from above:

# demo.py

import json

response = '[{"lastUpdated":0,"id":"123","protocol":"https","hostName":"ipdatas","port":"000","serverName":"training-1-t","status":"online","serverType":"transparency","enabled":true},{"lastUpdated":0,"id":"456","protocol":"https","hostName":"urldatas","port":"000","serverName":"graphql","status":"disconnected","serverType":"quapi","enabled":false},{"lastUpdated":0,"id":"789","protocol":"https","hostName":"ipdatas","port":"000","serverName":null,"status":"online","serverType":"directive","enabled":true}]'

# Parse the URL response as JSON
response_dict = json.loads(response)

transparent_ids = []

# Loop over that response.
for item in response_dict:
    # If the item's serverType is "transparency".
    if item.get("serverType", "").lower() == "transparency":
        # Store the item's id.
        transparent_ids.append(item["id"])

print(transparent_ids)

Running python3 demo.py returns back ['123'] which is the expected result since only the item with an id of 123 has a serverType of transparency.

After sending that to them they replied back saying it worked and thanked me.

How would you have solved this problem in either Python or your favorite programming language? Let me know down below in the comments.

Takeaways

Once you break your problem up into pseudo code, if needed you could Google for each step in plain English and solve each step with real code as you go. It becomes an outline to your program and helps you define what you even need to solve. I think this is why Googling and general research skills are really important.

Also, unknown unknowns can make problems look more complex than they really are.

In this case the person writing in thought that text was unstructured instead of JSON. Having to parse that as a plain text string would have been quite a bit more complicated. You could perhaps split on ,{ to get each item and continue parsing from there but this would have been riddled with edge cases.

I could see why they got stuck for a while going with that approach.

Live Coding Video

Timestamps

  • 0:58 – I do this all the time in my day to day
  • 1:39 – Being exposed to the problem in written form
  • 3:43 – What did they try so far?
  • 4:34 – Understanding the problem based on their email
  • 5:42 – Busting out the pseudo code
  • 8:41 – Live coding the working solution
  • 9:03 – Parsing the site response as JSON
  • 10:37 – Loop over the list of dictionaries
  • 11:02 – Only do something if the serverType is transparency
  • 13:26 – Store the transparent ids in a new variable
  • 15:38 – Now would be a good time to write some tests
  • 15:43 – Making the transparency check more robust
  • 19:59 – Reviewing the pseudo code and mentioning functional programming
  • 22:05 – Takeaways

What workflows do you do to implement real life features? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments