用于解答算法题目的Python3代码框架作者:杜逸先

简介:

前言

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

Python代码

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


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

VS Code代码片段

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

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

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


 
 
  1. /* 
  2.    // Place your snippets for Python here. Each snippet is defined under a snippet name and has a prefix, body and  
  3.    // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
  4.    // $1, $2 for tab stops, ${id} and ${id:label} and ${1:label} for variables. Variables with the same id are connected. 
  5.    // Example: 
  6.    "Print to console": { 
  7.       "prefix""log"
  8.       "body": [ 
  9.           "console.log('$1');"
  10.           "$2" 
  11.       ], 
  12.       "description""Log output to console" 
  13.   } 
  14. */ 
  15. "Simple Console Program With Data Input And Output": { 
  16.       "prefix""simple"
  17.       "body": ["\"\"\"Simple Console Program With Data Input And Output.\"\"\"\nimport sys\n\ndef read_int():\n \"\"\"Read a seris of numbers.\"\"\"\n return list(map(int, sys.stdin.readline().split()))\n\n\ndef read_float():\n \"\"\"Read a seris of float numbers.\"\"\"\n return list(map(float, sys.stdin.readline().split()))\n\n\ndef read_word():\n \"\"\"Read a seris of string.\"\"\"\n return list(map(str, sys.stdin.readline().split()))\n\n\ndef combine_with(seq, sep=' ', num=None):\n \"\"\"Combine list enum with a character and return the string object\"\"\"\n res = sep.join(list(map(str, seq)))\n if num is not None:\n res = str(seq[0])\n for element in range(1, len(seq)):\n res += sep + str(seq[element]) if element % num != 0 else '\\n' + str(seq[element])\n return res\n\n\ndef main():\n \"\"\"The main function.\"\"\"\n pass\n\n\nif __name__ == '__main__':\n sys.exit(int(main() or 0))\n" 
  18.       ], 
  19.       "description""Simple Console Program With Data Input And Output" 
  20.   } 

总结

虽然Python不是特别适合解答算法题目这种性能要求很高的场景,但是在一些模拟题目如各种排队型和字符串处理的条件下,使用Python可以极大地提高解体效率,另外还可以使用cimport使用C语言的数据结构和Python的语法特性,效率不弱于原生C代码。


作者:杜逸先

来源:51CTO

相关文章
|
7月前
|
算法 搜索推荐 JavaScript
基于python智能推荐算法的全屋定制系统
本研究聚焦基于智能推荐算法的全屋定制平台网站设计,旨在解决消费者在个性化定制中面临的选择难题。通过整合Django、Vue、Python与MySQL等技术,构建集家装设计、材料推荐、家具搭配于一体的一站式智能服务平台,提升用户体验与行业数字化水平。
|
7月前
|
机器学习/深度学习 算法 机器人
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
724 0
|
7月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
570 0
|
7月前
|
存储 Java 数据处理
(numpy)Python做数据处理必备框架!(一):认识numpy;从概念层面开始学习ndarray数组:形状、数组转置、数值范围、矩阵...
Numpy是什么? numpy是Python中科学计算的基础包。 它是一个Python库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种方法,包括数学、逻辑、形状操作、排序、选择、I/0 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。 Numpy能做什么? numpy的部分功能如下: ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++
633 1
|
7月前
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
704 0
|
7月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
384 0
|
7月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
379 100
|
7月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
570 95
|
7月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
449 88
|
7月前
|
机器学习/深度学习 算法 机器人
使用哈里斯角Harris和SIFT算法来实现局部特征匹配(Matlab代码实现)
使用哈里斯角Harris和SIFT算法来实现局部特征匹配(Matlab代码实现)
347 8

热门文章

最新文章

推荐镜像

更多