当前位置:首页 > 文章列表 > 文章 > python教程 > 软件工程师访谈 - #EIS CLI

软件工程师访谈 - #EIS CLI

来源:dev.to 2024-12-14 11:37:03 0浏览 收藏

本篇文章给大家分享《软件工程师访谈 - #EIS CLI》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

软件工程师访谈 - #EIS CLI

介绍

这是软件工程师访谈系列的第三篇文章。我带来了几年前做过的挑战,并且实际上得到了这个职位 - 涉及其他技术面试,例如过去的经验筛选。

如果您错过了本系列之前的帖子,可以在这里找到它们。

挑战

这个挑战也是一项带回家的编码任务,我必须开发一个 cli 程序来查询 oeis(整数序列在线百科全书)并返回结果总数以及第一个结果的名称查询返回五个序列。

值得庆幸的是,oeis 查询系统包含 json 输出格式,因此您可以通过调用 url 并将序列作为查询字符串传递来获取结果。

输入和输出示例:

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).

注意:此结果已过时!

解决挑战

解决这一挑战的计划如下:

  • 从将作为 cli 入口点的 python 文件开始
    • 它应该接收一个以空格分隔的数字列表作为参数
  • 创建一个客户端文件,负责从 oeis 查询系统获取数据
  • 一个格式化程序,负责返回为控制台格式化的输出

由于这是一个编码挑战,我将使用 poetry 来帮助我创建项目的结构,并方便任何人运行它。您可以在他们的网站上查看如何安装和使用 poetry。

我将首先使用以下内容创建包:

poetry new oeis

这将创建一个名为 oeis 的文件夹,其中包含 poetry 的配置文件、一个测试文件夹和一个也称为 oeis 的文件夹,该文件夹将成为我们项目的根目录。

我还将添加一个名为 click 的可选包,它有助于构建 cli 工具。这不是必需的,可以用 python 中的其他本机工具替换,尽管不太优雅。

在项目文件夹中,运行:

poetry add click

这会将 click 添加为我们项目的依赖项。

现在我们可以移动到入口点文件。如果你打开文件夹 oeis/oeis,你会看到已经有一个 __init__.py 文件。让我们更新它以导入 click,以及使用以下命令调用的主函数:

# oeis/oeis/__init__.py

import click


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


if __name__ == "__main__":
    oeis()

这是我们 cli 的起点。看到@click.command了吗?这是来自 click 的包装器,它将帮助我们将 oeis 定义为命令。

现在,还记得我们需要接收以空格分隔的数字序列吗?我们需要将其添加为参数。 click 有一个选项:

# oeis/oeis/__init__.py

import click


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


if __name__ == "__main__":
    oeis()

这将添加一个名为序列的参数,并且 nargs=-1 选项告诉单击它将用空格分隔。我添加了一个打印,以便我们可以测试参数是否正确传递。

为了告诉 poetry 我们有一个命令,我们需要打开 pyproject.toml 并添加以下行:

# oeis/pyproject.toml

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

这是添加一个名为 oeis 的脚本,该脚本调用 oeis 模块上的 oeis 函数。现在,我们运行:

poetry install

这将让我们调用脚本。我们来尝试一下:

❯ poetry run oeis 1 2 3 4 5
('1', '2', '3', '4', '5')

完美,我们已经按照我们的预期解析了命令和参数!让我们继续讨论客户端。在oeis/oeis文件夹下,创建一个名为clients的文件夹、一个名为__init__.py的文件和一个名为oeis_client.py的文件。

如果我们期望在这个项目中拥有其他客户端,我们可以开发一个基本客户端类,但由于我们只有这一个,所以这可能被认为是过度设计。在 oeis 客户端类中,我们应该有一个基本 url,这是没有路径的 url,我们将使用它来查询它:

# oeis/oeis/clients/oeis_client.py

import requests

from urllib.parse import urlencode


class oeisclient:
    def __init__(self) -> none:
        self.base_url = "https://oeis.org/"

    def query_results(self, sequence: tuple[str]) -> list:
        url_params = self.build_url_params(sequence)
        full_url = self.base_url + "search?" + url_params

        response = requests.get(full_url)
        response.raise_for_status()
        return response.json()

    def build_url_params(self, sequence: tuple[str]) -> str:
        sequence_str = ",".join(sequence)
        params = {"q": sequence_str, "fmt": "json"}
        return urlencode(params)

如您所见,我们正在导入 requests 包。我们需要将它添加到 poetry 中才能使用它:

poetry add requests

现在,客户端有一个不会改变的基本 url。让我们深入研究其他方法:

  • 构建网址参数
    • 接收从 cli 作为参数传递的序列,并将其转换为以逗号分隔的数字字符串
    • 使用参数构建一个字典,q 是我们将运行的查询,fmt 是预期的输出格式
    • 最后,我们返回参数的 url 编码版本,这是确保我们的字符串与 url 兼容的好方法
  • 查询结果
    • 接收从 cli 作为参数传递的序列,通过 build_url_params 方法构建 url 编码的参数
    • 构建将用于查询数据的完整 url
    • 继续向构建的 url 发出请求,并引发我们未预料到的任何 http 状态
    • 返回 json 数据

我们还需要更新我们的主文件,以调用此方法:

# oeis/oeis/__init__.py

import click

from oeis.clients.oeis_client import oeisclient


oeis_client = oeisclient()


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


if __name__ == "__main__":
    oeis()

这里我们现在在方法外部构建一个客户端实例,因此它不会在每次调用命令时都创建一个实例,而是在命令内部调用它。

运行此命令会产生非常非常长的响应,因为 oeis 有数千个条目。由于我们只需要知道总大小和前五个条目,因此我们可以执行以下操作:

# oeis/oeis/__init__.py

import click

from oeis.clients.oeis_client import oeisclient


oeis_client = oeisclient()


@click.command()
@click.argument("sequence", nargs=-1)
def oeis(sequence: tuple[str]):
    data = oeis_client.query_results(sequence)
    size = len(data)
    top_five = data[:5]
    print(size)
    print(top_five)


if __name__ == "__main__":
    oeis()

运行这个已经比以前好得多了。我们现在打印总大小以及前五个(如果存在)条目。

但我们也不需要所有这些。让我们构建一个格式化程序来正确格式化我们的输出。创建一个名为 formatters 的文件夹,其中包含 __init__.py 文件和 oeis_formatter.py 文件。

# oeis/oeis/formatters/oeis_formatter.py

def format_output(query_result: list) -> str:
    size = len(query_result)
    top_five = query_result[:5]
    top_five_list = [f"{i+1}. {entry["name"]}" for i, entry in enumerate(top_five)]
    top_five_str = "\n".join(top_five_list)

    first_line = f"found {size} results. showing the first {len(top_five)}:\n"

    return first_line + top_five_str

该文件基本上将前五个结果格式化为我们想要的输出。让我们在主文件中使用它:

# oeis/oeis/__init__.py

import click

from oeis.clients.oeis_client import oeisclient
from oeis.formatters import oeis_formatter


oeis_client = oeisclient()


@click.command()
@click.argument("sequence", nargs=-1)
def oeis(sequence: tuple[str]):
    data = oeis_client.query_results(sequence)
    output = oeis_formatter.format_output(data)
    print(output)


if __name__ == "__main__":
    oeis()

如果您运行此代码,您现在将得到:

found 10 results. showing the first 5:
1. a(n) is the number of partitions of n (the partition numbers).
2. a(n) = floor(3^n / 2^n).
3. partition triangle a008284 read from right to left.
4. number of n-stacks with strictly receding walls, or the number of type a partitions of n in the sense of auluck (1951).
5. number of partitions of n into prime power parts (1 included); number of nonisomorphic abelian subgroups of symmetric group s_n.

它现在以我们期望的格式返回,但请注意它说找到了 10 个结果。这是错误的,如果您在 oeis 网站上搜索,您会看到更多结果。不幸的是,oeis api 进行了更新,结果不再返回包含结果数量的计数。不过,该计数仍然显示在文本格式的输出中。我们可以用它来知道有多少个结果。

为此,我们可以更改 url 以使用 fmt=text 和正则表达式来查找我们想要的值。让我们更新客户端代码以获取文本数据,并更新格式化程序以使用此数据,以便我们可以输出它。

# oeis/oeis/clients/oeis_client.py

import re
import requests

from urllib.parse import urlencode


class oeisclient:
    def __init__(self) -> none:
        self.base_url = "https://oeis.org/"
        self.count_regex = re.compile(r"showing .* of (\d*)")

    def query_results(self, sequence: tuple[str]) -> list:
        url_params = self.build_url_params(sequence, fmt="json")
        full_url = self.base_url + "search?" + url_params

        response = requests.get(full_url)
        response.raise_for_status()
        return response.json()

    def get_count(self, sequence: tuple[str]) -> str:
        url_params = self.build_url_params(sequence, fmt="text")
        full_url = self.base_url + "search?" + url_params

        response = requests.get(full_url)
        response.raise_for_status()
        return self.get_response_count(response.text)

    def build_url_params(self, sequence: tuple[str], fmt: str) -> str:
        sequence_str = ",".join(sequence)
        params = {"q": sequence_str, "fmt": fmt}
        return urlencode(params)

    def get_response_count(self, response_text: str) -> str:
        match = self.count_regex.search(response_text)

        if not match:
            raise exception("count not found!")

        return match.group(1)

如您所见,我们添加了两个新方法:

  • 获取计数
    • 将为文本 api 构建参数,并将其传递给使用正则表达式查找我们正在搜索的数字的方法
  • 获取响应计数
    • 将使用类 init 中内置的正则表达式来执行搜索并获取第一组
# oeis/oeis/formatters/oeis_formatter.py

def format_output(query_result: list, count: str) -> str:
    top_five = query_result[:5]
    top_five_list = [f"{i+1}. {entry["name"]}" for i, entry in enumerate(top_five)]
    top_five_str = "\n".join(top_five_list)

    first_line = f"found {count} results. showing the first {len(top_five)}:\n"

    return first_line + top_five_str

在这个文件中,我们只为方法添加了一个新的参数,并用它代替了查询结果的长度。

# oeis/oeis/__init__.py

import click

from oeis.clients.oeis_client import oeisclient
from oeis.formatters import oeis_formatter


oeis_client = oeisclient()


@click.command()
@click.argument("sequence", nargs=-1)
def oeis(sequence: tuple[str]):
    data = oeis_client.query_results(sequence)
    count = oeis_client.get_count(sequence)
    output = oeis_formatter.format_output(data, count)
    print(output)


if __name__ == "__main__":
    oeis()

这里我们只是在客户端调用新方法,并将信息传递给格式化程序。再次运行它会产生我们期望的输出:

❯ poetry run oeis 1 2 3 4 5
Found 7821 results. Showing the first 5:
1. The positive integers. Also called the natural numbers, the whole numbers or the counting numbers, but these terms are ambiguous.
2. Digital sum (i.e., sum of digits) of n; also called digsum(n).
3. Powers of primes. Alternatively, 1 and the prime powers (p^k, p prime, k >= 1).
4. The nonnegative integers.
5. Palindromes in base 10.

代码已经基本准备好了。但对于真正的挑战,请记住尽可能使用 git,进行小型提交,当然,添加单元测试、代码格式化库、类型检查器以及您认为需要的任何其他内容。

祝你好运!

到这里,我们也就讲完了《软件工程师访谈 - #EIS CLI》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
PHP中如何声明和使用字节数组?PHP中如何声明和使用字节数组?
上一篇
PHP中如何声明和使用字节数组?
Python 函数切片操作返回空列表,问题出在哪?
下一篇
Python 函数切片操作返回空列表,问题出在哪?
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 毕业宝AIGC检测:AI生成内容检测工具,助力学术诚信
    毕业宝AIGC检测
    毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
    3次使用
  • AI Make Song:零门槛AI音乐创作平台,助你轻松制作个性化音乐
    AI Make Song
    AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
    26次使用
  • SongGenerator.io:零门槛AI音乐生成器,快速创作高质量音乐
    SongGenerator
    探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
    21次使用
  •  BeArt AI换脸:免费在线工具,轻松实现照片、视频、GIF换脸
    BeArt AI换脸
    探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
    24次使用
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    23次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码