潘振中
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 期末考前幾個python必懂重點 ###### tags: `期末` `Python` `蟒蛇` `可怕的大蟒蛇` `depressed` `catastrophe` ## 前言 搭配上一篇:<a href="https://hackmd.io/0fT5WbSuRTqoIK_J4HO7Iw">期中考前的幾個Python必懂重點</a><br /> <font color="#FF2D2D">紅色</font>是重點 <<font color="#2CBFE0 ">藍色</font>>是讓你變動的東西 歡迎分享,代碼推薦上編譯器實際體驗一次 有問題能在下面提問 這裡只是我考試或寫作業時覺得很常用的重點整理 詳細資料請參閱 <a href="https://letranger.github.io/PythonCourse/PythonBasic.html" target="_blank">Python教材PDF</a><br /> ## 資料型別 ### 字典 常用於資料統計或建表 但我不常用就是了 ¯\_( ͡° ͜ʖ ͡°)_/¯ **語法如下:** <<font color="#2CBFE0 ">字典名稱</font>> = {<<font color="#2CBFE0 ">資料1</font>> : <<font color="#2CBFE0 ">對應值1</font>>,<<font color="#2CBFE0 ">資料2</font>> : <<font color="#2CBFE0 ">對應值2</font>>,...}</font> <font color="8F8F8F">#字典是無序的</font> **字典基本操作:** <<font color="#2CBFE0 ">字典名稱</font>>[<<font color="#2CBFE0 ">新建資料</font>>] = <<font color="2CBFE0">對應值</font>> <font color="#8F8F8F">#新增值</font> <<font color="#2CBFE0 ">字典名稱</font>>[<<font color="#2CBFE0 ">原資料</font>>] = <<font color="2CBFE0">新值</font>>   <font color="#8F8F8F">#修改值</font> del <<font color="#2CBFE0 ">字典名稱</font>>[<<font color="#2CBFE0 ">新建資料</font>>]  <font color="#8F8F8F">#刪除值</font> <<font color="#2CBFE0 ">字典名稱</font>>.get(<<font color="#2CBFE0 ">資料名稱</font>>) <font color="#8F8F8F">#取值 (key不存在時返回默認值(None))</font> <<font color="#2CBFE0 ">字典名稱</font>>[<<font color="#2CBFE0 ">資料名稱</font>>]   <font color="#8F8F8F">#也是取值 (key不存在時觸發KeyError)</font> <<font color="#2CBFE0 ">字典名稱</font>>.items()  <font color="#8F8F8F">#取整個字典物件 (class為dict_items)</font> <<font color="#2CBFE0 ">字典名稱</font>>.keys()  <font color="#8F8F8F">#取整個字典資料 (class為dict_keys)</font> <<font color="#2CBFE0 ">字典名稱</font>>.values()  <font color="#8F8F8F">#取整個字典值 (class為dict_values)</font> <<font color="#2CBFE0 ">字典名稱</font>>.pop(<<font color="#2CBFE0 ">資料名稱</font>>) <font color="#8F8F8F">#取出和刪除字典指定元素</font> <<font color="#2CBFE0 ">字典名稱</font>>.popitem()  <font color="#8F8F8F">#取出和刪除字典最後一組元素</font> 以下示範幾種常用轉換方式 ```python= dic = {'a':1,'b':2,'c':3,'d':4} #轉換及列印keys print(list(dic.keys())) #轉換及列印values print(list(dic.values())) #以key取值 print(dic['a']) print(dic.get('a')) #以值取key (利用list-index) keys = list(dic.keys()) values = list(dic.values()) Index = values.index(2) Value = keys[Index] print(Value) ``` > <font color="#00CC00">即興範例</font> > 輸入產品名稱 > 輸出產品價格 ```python= groceries = {'17世紀的骨董湯匙':5,'超炫的喝汽水涼帽':100,'古代瑞士皇后拿過的舊傘':50} print(groceries.get('超炫的喝汽水涼帽')) ``` #### <font>走訪字典</font> ```python= groceries = {'17世紀的骨董湯匙':5,'超炫的喝汽水涼帽':100,'古代瑞士皇后拿過的舊傘':50} for i,j in groceries.items(): print(i,j) ``` ### <font color="FF2D2D">集合</font> 集合是這次考試的一大重點 務必熟知特性及基本操作 **語法如下:** <<font color="#2CBFE0 ">集合名稱</font>> = {<<font color="#2CBFE0 ">元素</font>>,<<font color="#2CBFE0 ">元素</font>>,<<font color="#2CBFE0 ">元素</font>>,...}</font> <font color="#FF2D2D">**集合是無序且元素單一的(移除重複元素)**</font> <font color="#8F8F8F">#建立空集合</font> <<font color="#2CBFE0 ">集合名稱</font>> = set() <font color="#8F8F8F">#不可使用 <name> = { } 這樣是字典形式</font> **集合基本操作:** <<font color="#2CBFE0 ">集合名稱</font>>.add(<<font color="#2CBFE0 ">元素</font>>)   <font color="#8F8F8F">#新增元素</font> <<font color="#2CBFE0 ">集合名稱</font>>.remove(<<font color="#2CBFE0 ">元素</font>>)  <font color="#8F8F8F">#移除元素</font> len(<<font color="#2CBFE0 ">集合名稱</font>>)   <font color="#8F8F8F">#return長度</font> sum(<<font color="#2CBFE0 ">集合名稱</font>>)  <font color="#8F8F8F">#return總和(元素為數字時)</font> max(<<font color="#2CBFE0 ">集合名稱</font>>)  <font color="#8F8F8F">#return最小值</font> min(<<font color="#2CBFE0 ">集合名稱</font>>)  <font color="#8F8F8F">#return最大值</font> **集合運算子** <<font color="#2CBFE0 ">集合1</font>> | <<font color="#2CBFE0 ">集合2</font>>  <font color="#8F8F8F">#聯集</font> <<font color="#2CBFE0 ">集合1</font>> & <<font color="#2CBFE0 ">集合2</font>> <font color="#8F8F8F">#交集</font> <<font color="#2CBFE0 ">集合1</font>> - <<font color="#2CBFE0 ">集合2</font>>  <font color="#8F8F8F">#差集</font> <<font color="#2CBFE0 ">集合1</font>> ^ <<font color="#2CBFE0 ">集合2</font>>  <font color="#8F8F8F">#互斥</font> <<font color="#2CBFE0 ">集合1</font>> in <<font color="#2CBFE0 ">集合2</font>>  <font color="#8F8F8F">#屬於</font> 集合也可以在其他資料型別之間轉換 ```python= list1 = [1,1,1,3,3,5,6,6,4,4,4] set1 = set(list1) #一種元素只會保留一個 list2 = list(set1) #可以利用set特性排除重複元素 print(list1,list2) ``` > <font color="#00CC00">8D. 小孩才選擇,我全都要</font> > 第一行為N,代表接下來有N列資料 > 讀入N列,每列代表一集合。輸出以下資訊: > 所有集合的交集項目數 > 已排序之所有集合聯集項目。 > 測資1: > 3 > A,B,D,X,Q,M,G,C > B,C,Y,N,M,L,H > Q,C,Y,M,D,H > 輸出1: > 2 > ['A', 'B', 'C', 'D', 'G', 'H', 'L', 'M', 'N', 'Q', 'X', 'Y'] ```python= setlist = [set(list(input().split(','))) for _ in range(int(input()))] #系統會先偵測需求range(<value>)裡的input輸入請求,之後才進行setlist的列表創建 #建立交集 tem = setlist[0] for i in setlist: tem = tem & i ans1 = len(tem) #建立聯集 tem = setlist[0] for i in setlist: tem = tem | i ans2 = list(tem) print(ans1,sorted(ans2),sep = '\n') ``` > 如果你是lambda邪教或飛行義大利麵神教的成員 > 請參考我們 <font color="#1876F2">@籃球社py免修電神</font> 協助撰寫的一行解 ```python= (lambda x:print(len(set.intersection(*x)),sorted(set.union(*x)),sep='\n'))([set(list(input().split(','))) for _ in range(int(input()))]) #lambda用於回傳setlist分別給print函式裡面的兩個變數x #變數x前的*可以把list拆開(ex:set.union(set1,set2,set3,...)) ``` #### <font color="FF2D2D">不使用跌代或迴圈做全體聯集or交集的方法</font> **語法如下:** <<font color="#2CBFE0 ">集合名稱</font>>.intersection(<<font color="#2CBFE0 ">集合</font>>,...) <font color="#8F8F8F" size = 1>#交集,( )中為一個以上的集合物件,可使用星號*list拆開來讓括號可以讀取</font> <<font color="#2CBFE0 ">集合名稱</font>>.union(<<font color="#2CBFE0 ">集合</font>>,...) <font color="#8F8F8F" size = 1>#聯集,補充同上</font> 更多進階用法請參考<a href="https://www.delftstack.com/zh-tw/tutorial/python-3-basic-tutorial/data-type-sets/#%25E9%259B%2586%25E5%2590%2588%25E7%259A%2584%25E6%2593%258D%25E4%25BD%259C" target="_blank">此篇教學</a><br />傳入多個變數 (如list) 的星號用法請參考<a href="https://www.796t.com/content/1549642928.html" target="_blank">此篇教學</a><br /> > <font color="#00CC00">即興範例</font> > 輸入超多行資料(結尾EOF) > 輸出所有資料的聯集、交集 ```python= setlist = [] try: while True: setlist.append(set(list(input().split()))) except:pass print(sorted(setlist[0].union(*setlist))) #sorted的結果會轉為list print(sorted(set.intersection(*setlist))) #(method)也可以直接用set代替 ``` ## Function 函式 ### Function function可簡單分為三種 1. 內建function python本身內建的function print(),capitalize(),len() 都可以算是內建function 2. 外部function import numpy,import os,import panda 屬於第三方開發的函式庫 這些需要從外部引入函式庫的都算是外部function 3. 自定義function 通過def語法定義一段程式區塊 並於呼叫時執行(意指沒用到就不會執行) ### <font color="FF2D2D">自定義function</font> #### 基本用法 語法如下: def <<font color="#2CBFE0 ">函式名稱</font>>(<<font color="#2CBFE0 ">變數</font>>,...):   <<font color="#2CBFE0 ">主程式區</font>>   return <<font color="#2CBFE0 ">值</font>> <font color="#8F8F8F">#需要的話</font> <font color="#8F8F8F">#注意縮排</font> 呼叫(執行)時: <<font color="#2CBFE0 ">函式名稱</font>>(<<font color="#2CBFE0 ">傳入值</font>>,...)  宣告變數時 <<font color="#2CBFE0 ">變數</font>> = <<font color="#2CBFE0 ">函式名稱</font>>(<<font color="#2CBFE0 ">傳入值</font>>,...) <font color="#8F8F8F">#宣告為return的值</font> #### <font color="FF2D2D">return</font> 當function遇到return時,會立即終止並返還值 return可以是單個/多個值,值可以是各種資料型別(int,str,list...) > <font color="#00CC00">即興範例</font> > 使用埃式篩法進行質數檢查 ```python= n = int(input()) def primecheck(n): if n <= 0: return 'wrong range' elif n == 1: return '1是質數' for i in range(2,int(n**0.5)+1): if n % i == 0: return 'not prime' else: return 'prime' print(primecheck(n)) ``` ![](https://i.imgur.com/a9zc7XG.jpg =50%x) 在簡單的作業裡通常不會刻意把程式做成function ![](https://i.imgur.com/7YTkTZn.png =50%x) ### <font color="FF2D2D">區域變數和全域變數</font> 在使用自定義function的時候 要將值傳出函式通常使用return 無法直接在函式區外抓取func內的變數 此時func內定義的變數就屬於局域變數 ![](https://i.imgur.com/m2e9Bp9.jpg =60%x) ```python= i = 0 j = 1 def print1(): i = 5 j = 3 k = 7 print(i,j) def print2(): print(i,j) print1() print2() try: print(k) except: print('unavailable') ``` ```python= 5 3 #使用局域變數 0 1 #函式內查無變數-->抓取全域變數 navailable #抓不到局域變數 ``` 主程式無法直接抓取函式內的局域變數 ### <font color="FF2D2D">遞迴 Recursion</font> #### 語法如下: def <<font color="#2CBFE0 ">函式名稱</font>>(<<font color="#2CBFE0 ">變數</font>>,...):   <<font color="#2CBFE0 ">主程式區</font>>   return <<font color="#2CBFE0 ">函式名稱</font>>(<<font color="#2CBFE0 ">變數</font>>,...) 一個函式會通過呼叫自己進行重複動作 稱之為遞迴 #### 使用時機 一些loop與if else無法輕鬆解決的情況 > <font color="#00CC00">即興範例</font> > 兩種分別以迴圈和遞迴做成的階乘 ```python= n = int(input()) ans = 1 for i in range(n): ans *= i print(ans) ``` ```python= n = int(input()) ans = 1 def susi(n): if n <= 1: return 1 else: return n*susi(n-1) print(susi(n)) ``` 不小心把迴圈寫得比遞迴簡單了 ![](https://i.imgur.com/tIVpo6p.jpg =15%x) > <font color="#00CC00">即興範例</font> > 兩種分別以迴圈和遞迴做成的費氏數列 ```python= n = int(input()) a = 1 b = 1 c = 0 if n == 1: print(a) elif n == 2: print(b) else: for i in range(3,n+1): c = a + b a = b b = c print(c) ``` ```python= n = int(input()) def fe4(n): if n == 1: return 1 elif n == 2: return 1 else: return fe4(n-2) + fe4(n-1) print(fe4(n)) ``` 遞迴-費氏數列 流程圖 ![](https://i.imgur.com/66GLS23.jpg =70%x) 樹狀圖是一個很好理解遞迴運行方式的一個方法 ## 考試實用小技巧 ### 保守策略 以下是我的考試策略 1.分析問題: 了解題目在考什麼,統計、數學、生活應用之類的 2.拆分問題: 把大問題拆成小問題,把小問題嘗試步驟化 3.懷疑自我: 開始捫心自問:「我真的做得出來嗎,要不要跳過這題?」的時候,不要驚慌,不要害怕,跟著以下的步驟走 4.再次審題: 了解題目是否超出自身能力範圍,是否是複雜的遞迴、難以分析的數學問題、瞎雞巴的應用情形、免修仔故意出的演算法題目像動態規劃之類的 如果超出能力負荷,則換下一題並回到第一步 如果打算好重振旗鼓,建議把先前雜亂的程式刪掉重寫,並使用不同策略拆分題目 5.Debug: 某些極端測資目的在考驗你程式的全面性,可以在每一個步驟對變數做print做逐步檢查

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully