臺中一中39th電研社教學
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    --- title: Python第四週講義 臺中一中電研社 slideOptions: theme: sky transition: 'convex' --- <style> .w { color: #FFFFFF; font-size: 1px; left=100px; } h2{ color:#000080; } </style> <font color="#000080">Python 第四週講義</font> === >[name= 林德恩、陳睿倬][time= Nov 12,2021 ] ###### tags:`python` `tcirc39th` `社課` `臺中一中電研社` [TOC] --- ## <span class="blue">電研社</span> 社網:[tcirc.tw](https://tcirc.tw) online judge:[judge.tcirc.tw](https://judge.tcirc.tw) IG:[TCIRC_39th](https://www.instagram.com/tcirc_39th) --- <!-- append(), pop(), len(), insert(), index(), sort() pop(), clear() add() 比較運算子(== != > >= < <=), 邏輯運算子(and or not), 位元邏輯運算子(& | ~ ^ ) --> ## 函式(function) 函式是一種將功能先寫好,在後面可使其包裝起來,重複利用。 ex. ```python= print() .append() .sort() ``` ---- ### 自訂函式 我們可以自己寫一個函式,並自訂它的功能。 ---- #### 創建 ```python= def 函式名稱(參數1,參數2,參數3...): #參數數量可以0~∞ return 回傳值 #此行可寫可不寫,沒寫就只是不會回傳資料 ``` ---- #### 使用 在創建完就可以使用函式,並可以重複使用 ex. ```python= def a(x,y): print(x+y) a(1,2) ``` ---- #### 回傳值 在將函式放入其他函式或將它作為一個值時,必須有回傳值(return),在回傳之後,函式就會結束 ```python= def a(x,y): print(x+y) return x-y print(a(1,2)) b=a(3,5) print(b) ``` ---- **output** ``` 3 -1 8 -2 ``` ---- #### 遞迴 將函式多次在回傳值呼叫自己就是遞迴,多搭配if,else,elif使用 注意:在實作遞迴時要記得設置終止條件,否則會出現錯誤 ```python= def a(x,y): print(x,y,"/") if(x>y): return a(x-y,y+1) else: return 1 print(a(5,2)) ``` ---- 範例: [費波那契數列](https://zh.wikipedia.org/wiki/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0) f(n) = f(n-1) + f(n-2) f(0) = 0, f(1) = 1 錯誤的寫法: ```python= def fib(x): return fib(x-1) + fib(x-2) print(fib(9)) ``` output ``` RecursionError: maximum recursion depth exceeded ``` 因為沒有設定結束 ---- 正確寫法 ```python= def fib(x:int): if (x <= 1):return x # <-- stop condition return fib(x-1) + fib(x-2) # 0 1 2 3 4 5 6 7 8 9 print(fib(9)) # 0 1 1 2 3 5 8 13 21 34 ``` **output** ``` 34 ``` --- ## 物件(object) <!--有點難解釋--> 像數值、字串、list、函式都是物件 基本上所有東西都是物件 --- ## class(類別) <!--不知如何說清楚--> 可以import ex. int、random、string 注意,在寫class時,一定要寫初始化程式,定義屬性 \__init__ ---- ```python= class TCFSH: def __init__(self, id, name, grade): self.id = id self.name = name self.grade = grade self.score = None john = TCFSH(910943, "John", 2) print(john.id) print(john.name) print(john.grade) print(john.score) john.score = 80 print(john.score) ``` ---- **output** ``` 910943 John 2 None 80 ``` ---- ### 類別裡的函式 我們可在類別class裡定義函式,方便我們對物件更改,訪問屬性 ```python= class TCFSH: def __init__(self, id, name, grade): self.id = id self.name = name self.grade = grade self.score = None def show_inf(self): name = self.name # 在類別裡呼叫物件屬性用self print("show", name, "inf") print(self.id) print(self.name) print(self.grade) print(self.score) def change_std_score(self, score): self.score = score print(str(self.name)+"'s grade is", self.score ) john = TCFSH(910943, "John", 2) john.show_inf() # <-- 呼叫物件函式時,需要先打上 物件名稱.函式名稱 print("=========================") john.change_std_score(100) ``` ---- **output** ``` show John inf 910943 John 2 None ========================= John's grade is 100 ``` ---- ### 父類別、子類別 可以在class底下建立class在外層的是父類別,下一層的是子類別 以此類推,而呼叫子類別時要先呼叫父類別才能運作,中間如何呼叫內部的函式一樣用<span style="font-size:30px">.</span>隔開 ---- ```python= class a: class b: def __init__(self): self.z=1 def k(y): print(y) def __init__(self): self.w=1 def n(x): print(x**2) a.b.k(15) a.n(10) ``` ---- **output** ``` 15 100 ``` --- ## 樹(tree) 樹是一種電腦的資料結構,如同容器一樣可儲存資料,並有效地插入,搜尋資料 ![](https://i.imgur.com/gfch3G6.png =600x) [image link](https://www.google.com/url?sa=i&url=https%3A%2F%2Ftowardsdatascience.com%2F8-useful-tree-data-structures-worth-knowing-8532c7231e8c&psig=AOvVaw17gUi1A3LzTZQL70FFlEaX&ust=1636726156512000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCPCQpKK-kPQCFQAAAAAdAAAAABAD) ---- Root:根,最上面的一個點 Node:節點,相連的點 Parent:父節點 Child:子節點 Grandchild:子節點的子節點 Ancestor:在往上跨一代的節點都是該點的Ancestor(不含父節點) Descendant:在往下跨一代的節點都是該點的Descendant(不含子節點) ---- Subtree:子樹,下面有child的child Leaves:沒有child的子節點 Key:裡面的值 Edge:節點之間的連接 Sibling:兄弟節點 Level:由上往下算(ex.Level 1,Level 2,Level 3...) Hight:高度,由下往上算有幾層 Tree Degree:子節點數 ---- #### 二元樹(binary tree) 二元樹是樹的其中一種結構,它只有每一層只有兩個分支 習慣上認為兩個子樹是不同的tree(只有在二元樹) 二元樹(排序) ![](https://i.imgur.com/JYg3C6i.png) 排序後右邊的樹一定比左邊大,右子樹比左子樹大 [image link](https://www.google.com/url?sa=i&url=https%3A%2F%2Fithelp.ithome.com.tw%2Farticles%2F10205875&psig=AOvVaw1vT_qOt_Jj5MerGNK2x9ma&ust=1636726227746000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCPj3_8K-kPQCFQAAAAAdAAAAABAD) ---- 完美二元樹(Perfect Binary Tree):每一層都是最大節點數 完全二元樹(Complete Binary Tree):是完美二元樹或除了最後一層以外是滿的,並只連續缺少右子樹。 ---- <!--記得排版,我不清楚你的程式怕排錯了--> ```python= import random as r class binary_tree: def __init__(self, data): self.left = None self.right = None self.data = data def SetChild(self, n): if ( n.data > self.data): if (self.right == None): self.right = n return 0 else: self.right.SetChild(n) elif (n.data < self.data): if (self.left == None): self.left = n return 0 else: self.left.SetChild(n) def show(self): print("(", end = " ") if (self.left != None): self.left.show() #print(self.left.data) else: print(None, end = ", ") print(self.data, end = ", ") if(self.right != None): self.right.show() #print(self.right.data) else: print(None, end = ", ") print(")", end = " ") # set root a = [] n = r.randint(0, 10) a.append(n) a[0] = binary_tree(n) for i in range(1, 6): n = r.randint(0, 50) a.append(n) a[i] = binary_tree(a[i]) a[0].SetChild(a[i]) for i in a: print(i.data, end = " ") print("") a[0].show() ``` ---- output ``` 3 49 47 1 14 11 ( ( None, 1, None, ) 3, ( ( ( ( None, 11, None, ) 14, None, ) 47, None, ) 49, None, ) ) ``` <span class="w">1232</span>

    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