用于解答算法题目的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

相关文章
|
1天前
|
Python
Python中的装饰器:提升代码可读性与复用性
Python中的装饰器是一种强大的工具,能够提升代码的可读性和复用性。本文将深入探讨装饰器的原理、用法以及在实际项目中的应用,帮助读者更好地理解和利用这一特性,提升代码质量和开发效率。
|
1天前
|
算法 关系型数据库 C语言
卡尔曼滤波简介+ 算法实现代码(转)
卡尔曼滤波简介+ 算法实现代码(转)
12 4
|
2天前
|
监控 Python
Python中的装饰器:提升代码可读性与可维护性
Python中的装饰器是一种强大的工具,可以在不修改函数源代码的情况下,增加新的功能。本文将介绍装饰器的基本概念,以及如何使用装饰器来提升代码的可读性和可维护性。通过实例演示,读者将了解装饰器在各种场景下的灵活运用,从而更好地理解并应用于实际开发中。
|
2天前
|
缓存 Python
Python中的装饰器:提升代码可读性与灵活性
在Python编程中,装饰器是一种强大的工具,可以通过在函数或方法周围包装额外的功能来提升代码的可读性和灵活性。本文将深入探讨装饰器的概念、用法和实际应用,帮助读者更好地理解并运用这一Python编程的利器。
|
2天前
|
数据采集 NoSQL 中间件
python-scrapy框架(四)settings.py文件的用法详解实例
python-scrapy框架(四)settings.py文件的用法详解实例
8 0
|
2天前
|
存储 数据采集 数据库
python-scrapy框架(三)Pipeline文件的用法讲解
python-scrapy框架(三)Pipeline文件的用法讲解
6 0
|
2天前
|
存储 数据采集 JSON
python-scrapy框架(二)items文件夹的用法讲解
python-scrapy框架(二)items文件夹的用法讲解
10 0
|
2天前
|
数据采集 前端开发 中间件
python-scrapy框架(一)Spider文件夹的用法讲解
python-scrapy框架(一)Spider文件夹的用法讲解
9 0
|
2天前
|
运维 算法
基于改进遗传算法的配电网故障定位(matlab代码)
基于改进遗传算法的配电网故障定位(matlab代码)
|
2天前
|
算法 调度
基于多目标粒子群算法冷热电联供综合能源系统运行优化(matlab代码)
基于多目标粒子群算法冷热电联供综合能源系统运行优化(matlab代码)