资讯专栏INFORMATION COLUMN

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

Dr_Noooo / 2934人阅读

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

前言

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

Python代码

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

</>复制代码

  1. """Simple Console Program With Data Input And Output."""
  2. import sys
  3. import io
  4. def read_int():
  5. """Read a seris of numbers."""
  6. return list(map(int, sys.stdin.readline().split()))
  7. def test_read_int():
  8. """Test the read_int function"""
  9. test_file = io.StringIO("1 2 3
  10. ")
  11. sys.stdin = test_file
  12. assert read_int() == [1, 2, 3], "read_int error"
  13. def read_float():
  14. """Read a seris of float numbers."""
  15. return list(map(float, sys.stdin.readline().split()))
  16. def test_read_float():
  17. """Test the read_float function"""
  18. test_file = io.StringIO("1 2 3
  19. ")
  20. sys.stdin = test_file
  21. assert read_float() == [1.0, 2.0, 3.0], "read_float error"
  22. def read_word():
  23. """Read a seris of string."""
  24. return list(map(str, sys.stdin.readline().split()))
  25. def test_read_word():
  26. """Test the read_word function"""
  27. test_file = io.StringIO("1 2 3
  28. ")
  29. sys.stdin = test_file
  30. assert read_word() == ["1", "2", "3"], "read_word error"
  31. def combine_with(seq, sep=" ", num=None):
  32. """Combine list enum with a character and return the string object"""
  33. res = sep.join(list(map(str, seq)))
  34. if num is not None:
  35. res = str(seq[0])
  36. for element in range(1, len(seq)):
  37. res += sep +
  38. str(seq[element]) if element % num != 0 else "
  39. " +
  40. str(seq[element])
  41. return res
  42. def test_combile_with():
  43. """Test the combile_with function."""
  44. assert combine_with([1, 2, 3, 4, 5], "*", 2) == """1*2
  45. 3*4
  46. 5""", "combine_with error."
  47. def main():
  48. """The main function."""
  49. pass
  50. if __name__ == "__main__":
  51. sys.exit(int(main() or 0))
VS Code代码片段

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

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

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

</>复制代码

  1. {
  2. /*
  3. // Place your snippets for Python here. Each snippet is defined under a snippet name and has a prefix, body and
  4. // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
  5. // $1, $2 for tab stops, ${id} and ${id:label} and ${1:label} for variables. Variables with the same id are connected.
  6. // Example:
  7. "Print to console": {
  8. "prefix": "log",
  9. "body": [
  10. "console.log("$1");",
  11. "$2"
  12. ],
  13. "description": "Log output to console"
  14. }
  15. */
  16. "Simple Console Program With Data Input And Output": {
  17. "prefix": "simple",
  18. "body": [""""Simple Console Program With Data Input And Output."""
  19. import sys
  20. def read_int():
  21. """Read a seris of numbers."""
  22. return list(map(int, sys.stdin.readline().split()))
  23. def read_float():
  24. """Read a seris of float numbers."""
  25. return list(map(float, sys.stdin.readline().split()))
  26. def read_word():
  27. """Read a seris of string."""
  28. return list(map(str, sys.stdin.readline().split()))
  29. def combine_with(seq, sep=" ", num=None):
  30. """Combine list enum with a character and return the string object"""
  31. res = sep.join(list(map(str, seq)))
  32. if num is not None:
  33. res = str(seq[0])
  34. for element in range(1, len(seq)):
  35. res += sep + str(seq[element]) if element % num != 0 else "
  36. " + str(seq[element])
  37. return res
  38. def main():
  39. """The main function."""
  40. pass
  41. if __name__ == "__main__":
  42. sys.exit(int(main() or 0))
  43. "
  44. ],
  45. "description": "Simple Console Program With Data Input And Output"
  46. }
  47. }```
  48. 然后再编写Python代码的时候,键入"simple"就可以自动输入以上模板。
  49. ![](https://static.oschina.net/uploads/img/201608/04182804_9GZn.png "在这里输入图片标题")
  50. # 总结

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

转载请注明本文地址: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元查看
<