search
HomeBackend DevelopmentPython TutorialSoftware Engineer Interviews - #EIS CLI

Software Engineer Interviews - #EIS CLI

Introduction

This is the third post of the Software Engineer Interviews series. I have brought a challenge I did a few years ago, and actually got the position - other tech interviews were involved, such as a past experience screening.

If you've missed the previous posts on this series, you can find them here.

The Challenge

This challenge was also a take-home coding task, where I had to develop a CLI program that would query the OEIS (On-Line Encyclopedia of Integer Sequences) and return the total number of results, and the name of the first five sequences returned by the query.

Thankfully, the OEIS query system includes a JSON output format, so you can get the results by calling the url and passing the sequence as a query string.

Example input and output:

oeis 1 1 2 3 5 7
Found 1096 results. Showing first five:
1. The prime numbers.
2. a(n) is the number of partitions of n (the partition numbers).
3. Prime numbers at the beginning of the 20th century (today 1 is no longer regarded as a prime).
4. Palindromic primes: prime numbers whose decimal expansion is a palindrome.
5. a(n) = floor(3^n / 2^n).

Note: this result is outdated!

Solving the Challenge

The plan to solve this challenge is the following:

  • Start with a Python file that will be the CLI entrypoint
    • It should receive a list of numbers separated by spaces as argument
  • Create a client file that will be responsible to fetch data from the OEIS query system
  • A formatter that will take care of returning the output formatted for the console

Since this is a coding challenge, I will be using Poetry to help me create the structure of the project, and to facilitate anyone running it. You can check how to install and use Poetry on their website.

I’ll start by creating the package with:

poetry new oeis

This will create a folder called oeis, which will contain the Poetry’s configuration file, a test folder, and a folder also called oeis, which will be the root of our project.

I will also add an optional package, called Click, which helps building CLI tools. This is not required, and can be replaced by other native tools from Python, although less elegant.

Inside the project’s folder, run:

poetry add click

This will add click as a dependency to our project.

Now we can move to our entrypoint file. If you open the folder oeis/oeis, you will see there’s already an __init__.py file. Let’s update it to import Click, and a main function to be called with the command:

# oeis/oeis/__init__.py

import click


@click.command()
def oeis():
    pass


if __name__ == "__main__":
    oeis()

This is the starting point to our CLI. See the @click.command? This is a wrapper from click, which will help us define oeis as a command.

Now, remember we need to receive the sequence of numbers, separated by a space? We need to add this as an argument. Click has an option for that:

oeis 1 1 2 3 5 7

This will add an argument called sequence, and the nargs=-1 option tells click it will be separated by spaces. I added a print so we can test the argument is being passed correctly.

To tell Poetry that we have a command, we need to open pyproject.toml and add the following lines:

Found 1096 results. Showing first five:
1. The prime numbers.
2. a(n) is the number of partitions of n (the partition numbers).
3. Prime numbers at the beginning of the 20th century (today 1 is no longer regarded as a prime).
4. Palindromic primes: prime numbers whose decimal expansion is a palindrome.
5. a(n) = floor(3^n / 2^n).

This is adding a script called oeis, which calls the oeis function on the oeis module. Now, we run:

poetry new oeis

which will let us call the script. Let’s try it:

poetry add click

Perfect, we have the command and the arguments being parsed as we expected! Let's move on to the client. Under the oeis/oeis folder, create a folder called clients, a file called __init__.py and a file called oeis_client.py.

If we expected to have other clients in this project, we could develop a base client class, but since we will only have this single one, this could be considered over-engineering. In the OEIS client class, we should have a base URL, which is the URL without the paths, and that we will use to query it:

# oeis/oeis/__init__.py

import click


@click.command()
def oeis():
    pass


if __name__ == "__main__":
    oeis()

As you can see, we are importing the requests package. We need to add it to Poetry before we can use it:

# oeis/oeis/__init__.py

import click


@click.command()
@click.argument("sequence", nargs=-1)
def oeis(sequence: tuple[str]):
    print(sequence)


if __name__ == "__main__":
    oeis()

Now, the client has a base url which does not change. Let's dive into the other methods:

  • build_url_params
    • Receives the sequence passed as argument from the CLI, and transforms it into a string of numbers separated by a comma
    • Builds a dict with the params, the q being the query we will run, and fmt being the output format expected
    • Lastly, we return the URL encoded version of the params, which is a nice way to ensure our string is compatible with URLs
  • query_results
    • Receives the sequence passed as argument from the CLI, builds the url encoded params through the build_url_params method
    • Builds the full URL which will be used to query the data
    • Proceeds with the request to the URL built, and raises for any HTTP status that we didn’t expect
    • Returns the JSON data

We also need to update our main file, to call this method:

# oeis/pyproject.toml

[tool.poetry.scripts]
oeis = "oeis:oeis"

Here we are now building a client instance, outside the method, so it doesn’t create an instance every time the command is called, and calling it inside the command.

Running this results in a very, very long response, since the OEIS has thousands of entries. As we only need to know the total size and the top five entries, we can do the following:

poetry install

Running this is already way better than before. We now print the total size, and the top five (if they exist) entries.

But we also don’t need all of that. Let's build a formatter to correctly format our output. Create a folder called formatters, which will have a __init__.py file and a oeis_formatter.py file.

oeis 1 1 2 3 5 7

This file is basically formatting the top five results into what we want for the output. Let’s use it in our main file:

Found 1096 results. Showing first five:
1. The prime numbers.
2. a(n) is the number of partitions of n (the partition numbers).
3. Prime numbers at the beginning of the 20th century (today 1 is no longer regarded as a prime).
4. Palindromic primes: prime numbers whose decimal expansion is a palindrome.
5. a(n) = floor(3^n / 2^n).

If you run this code, you will get this now:

poetry new oeis

It is now returning with the format we expect, but notice that it says it found 10 results. This is wrong, if you search on the OEIS website you will see there are way more results. Unfortunately, there was an update to OEIS API and the result no longer returns a count with the number of results. This count still shows up on the text formatted output, though. We can use it to know how many results there are.

To do this, we can change the URL to use the fmt=text, and a regex to find the value we want. Let’s update the client code to fetch the text data, and the formatter to use this data so we can output it.

poetry add click

As you can see, we added two new methods:

  • get_count
    • Will build the params for the text API, and pass it to the method which will use regex to find the number we are searching for
  • get_response_count
    • Will use the regex built in the class’ init to perform a search and get the first group
# oeis/oeis/__init__.py

import click


@click.command()
def oeis():
    pass


if __name__ == "__main__":
    oeis()

In this file, we only added a new param for the method, and used it instead of the length of the query result.

# oeis/oeis/__init__.py

import click


@click.command()
@click.argument("sequence", nargs=-1)
def oeis(sequence: tuple[str]):
    print(sequence)


if __name__ == "__main__":
    oeis()

Here we are just calling the new method on the client, and passing the information to the formatter. Running it again results in the output we were expecting:

# oeis/pyproject.toml

[tool.poetry.scripts]
oeis = "oeis:oeis"

The code is basically ready. But for a real challenge, remember to use Git when possible, do small commits, and of course, add unit tests, code formatting libs, type checkers, and whatever else you feel you will need.

Good luck!

The above is the detailed content of Software Engineer Interviews - #EIS CLI. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment