用於解答演算法題目的Python3代碼架構,演算法python3

來源:互聯網
上載者:User

用於解答演算法題目的Python3代碼架構,演算法python3
前言

最近在實習,任務並不是很重,就利用閑暇時間使用Python3在PAT網站上刷題,並致力於使用Python3的特性和函數式編程的理念,其中大部分題目都有著類似的輸入輸出格式,例如一行讀入若干個數字,字串,每行輸出多少個字串等等,所以產生了很多重複的代碼。

Python代碼

於是我就利用VS Code的程式碼片段功能編寫了一個用於處理這些輸入輸出的代碼架構,並加入了測試功能(寫函數前先寫測試時正確的事情)。代碼如下

"""Simple Console Program With Data Input And Output."""import sysimport iodef 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\n")    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\n")    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\n")    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 '\n' + \                str(seq[element])    return resdef 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."""    passif __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.\"\"\"\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"      ],      "description": "Simple Console Program With Data Input And Output"  }}
    然後再編寫Python代碼的時候,鍵入"simple"就可以自動輸入以上模板。

總結

雖然Python不是特別適合解答演算法題目這種效能要求很高的情境,但是在一些類比題目如各種排隊型和字串處理的條件下,使用Python可以極大地提高解體效率,另外還可以使用cimport使用C語言的資料結構和Python的文法特性,效率不弱於原生C代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.