资讯专栏INFORMATION COLUMN

用于解答算法题目的Python3代码框架

Dr_Noooo / 2724人阅读

摘要:代码于是我就利用的代码片段功能编写了一个用于处理这些输入输出的代码框架,并加入了测试功能写函数前先写测试时正确的事情。

前言

最近在实习,任务并不是很重,就利用闲暇时间使用Python3在PAT网站上刷题,并致力于使用Python3的特性和函数式编程的理念,其中大部分题目都有着类似的输入输出格式,例如一行读入若干个数字,字符串,每行输出多少个字符串等等,所以产生了很多重复的代码。

Python代码

于是我就利用VS Code的代码片段功能编写了一个用于处理这些输入输出的代码框架,并加入了测试功能(写函数前先写测试时正确的事情)。代码如下

"""Simple Console Program With Data Input And Output."""
import sys
import io


def read_int():
    """Read a seris of numbers."""
    return list(map(int, sys.stdin.readline().split()))


def test_read_int():
    """Test the read_int function"""
    test_file = io.StringIO("1 2 3
")
    sys.stdin = test_file
    assert read_int() == [1, 2, 3], "read_int error"


def read_float():
    """Read a seris of float numbers."""
    return list(map(float, sys.stdin.readline().split()))


def test_read_float():
    """Test the read_float function"""
    test_file = io.StringIO("1 2 3
")
    sys.stdin = test_file
    assert read_float() == [1.0, 2.0, 3.0], "read_float error"


def read_word():
    """Read a seris of string."""
    return list(map(str, sys.stdin.readline().split()))


def test_read_word():
    """Test the read_word function"""
    test_file = io.StringIO("1 2 3
")
    sys.stdin = test_file
    assert read_word() == ["1", "2", "3"], "read_word error"


def combine_with(seq, sep=" ", num=None):
    """Combine list enum with a character and return the string object"""
    res = sep.join(list(map(str, seq)))
    if num is not None:
        res = str(seq[0])
        for element in range(1, len(seq)):
            res += sep + 
                str(seq[element]) if element % num != 0 else "
" + 
                str(seq[element])
    return res


def test_combile_with():
    """Test the combile_with function."""
    assert combine_with([1, 2, 3, 4, 5], "*", 2) == """1*2
3*4
5""", "combine_with error."


def main():
    """The main function."""
    pass


if __name__ == "__main__":
    sys.exit(int(main() or 0))
VS Code代码片段

添加到VS Code的默认代码片段的操作大致如下:

文件->首选项->用户代码片段,选择Python

编辑"python.json"文件如以下内容

{
/*
     // Place your snippets for Python here. Each snippet is defined under a snippet name and has a prefix, body and 
     // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
     // $1, $2 for tab stops, ${id} and ${id:label} and ${1:label} for variables. Variables with the same id are connected.
     // Example:
     "Print to console": {
        "prefix": "log",
        "body": [
            "console.log("$1");",
            "$2"
        ],
        "description": "Log output to console"
    }
*/
 "Simple Console Program With Data Input And Output": {
        "prefix": "simple",
        "body": [""""Simple Console Program With Data Input And Output."""
import sys

def read_int():
    """Read a seris of numbers."""
    return list(map(int, sys.stdin.readline().split()))


def read_float():
    """Read a seris of float numbers."""
    return list(map(float, sys.stdin.readline().split()))


def read_word():
    """Read a seris of string."""
    return list(map(str, sys.stdin.readline().split()))


def combine_with(seq, sep=" ", num=None):
    """Combine list enum with a character and return the string object"""
    res = sep.join(list(map(str, seq)))
    if num is not None:
        res = str(seq[0])
        for element in range(1, len(seq)):
            res += sep + str(seq[element]) if element % num != 0 else "
" + str(seq[element])
    return res


def main():
    """The main function."""
    pass


if __name__ == "__main__":
    sys.exit(int(main() or 0))
"
        ],
        "description": "Simple Console Program With Data Input And Output"
    }
}```
 然后再编写Python代码的时候,键入"simple"就可以自动输入以上模板。

![](https://static.oschina.net/uploads/img/201608/04182804_9GZn.png "在这里输入图片标题")
# 总结

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/45510.html

相关文章

  • 【数据结构_浙江大学MOOC】第二讲 线性结构

    摘要:应直接使用原序列中的结点,返回归并后的带头结点的链表头指针。要求分别计算两个多项式的乘积与和,输出第一项为乘积的系数和指数,第二行为和的系数和指数。选定了表示方法后,考虑数据结构设计。选择链表在设计数据结构的时候有系数指数和指针结构指针。 函数题给出编译器为 C(gcc) 的解答,编程题给出编译器 C++(g++) 或 Python(python3) 的解答。 函数题 两个有序链表序...

    luxixing 评论0 收藏0
  • JS算法题之leetcode(1~10)

    摘要:先去空白,去掉空白之后取第一个字符,判断正负符号,若是英文直接返回,若数字则不取。回文数题目描述判断一个整数是否是回文数。回文数是指正序从左向右和倒序从右向左读都是一样的整数。 JS算法题之leetcode(1~10) 前言 一直以来,前端开发的知识储备在数据结构以及算法层面是有所暂缺的,可能归根于我们的前端开发的业务性质,但是我认为任何的编程岗位都离不开数据结构以及算法。因此,我作为...

    SoapEye 评论0 收藏0
  • 从简历被拒到收割今日头条 offer,我用一年时间破茧成蝶!

    摘要:正如我标题所说,简历被拒。看了我简历之后说头条竞争激烈,我背景不够,点到为止。。三准备面试其实从三月份投递简历开始准备面试到四月份收,也不过个月的时间,但这都是建立在我过去一年的积累啊。 本文是 无精疯 同学投稿的面试经历 关注微信公众号:进击的java程序员K,即可获取最新BAT面试资料一份 在此感谢 无精疯 同学的分享 目录: 印象中的头条 面试背景 准备面试 ...

    tracymac7 评论0 收藏0
  • 从简历被拒到收割今日头条 offer,我用一年时间破茧成蝶!

    摘要:正如我标题所说,简历被拒。看了我简历之后说头条竞争激烈,我背景不够,点到为止。。三准备面试其实从三月份投递简历开始准备面试到四月份收,也不过个月的时间,但这都是建立在我过去一年的积累啊。 本文是 无精疯 同学投稿的面试经历 关注微信公众号:进击的java程序员K,即可获取最新BAT面试资料一份 在此感谢 无精疯 同学的分享目录:印象中的头条面试背景准备面试头条一面(Java+项目)头条...

    wdzgege 评论0 收藏0

发表评论

0条评论

Dr_Noooo

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<