<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mindy Huang on Medium]]></title>
        <description><![CDATA[Stories by Mindy Huang on Medium]]></description>
        <link>https://medium.com/@hot50773?source=rss-9bea08323a27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Y8eFmI23Hy7vIDf7</url>
            <title>Stories by Mindy Huang on Medium</title>
            <link>https://medium.com/@hot50773?source=rss-9bea08323a27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:24:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hot50773/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[使用 SQLAlchemy 在資料庫中建立資料（一）]]></title>
            <link>https://hot50773.medium.com/%E5%9F%BA%E7%A4%8E%E8%B3%87%E6%96%99%E5%BA%AB%E6%93%8D%E4%BD%9C-%E4%BD%BF%E7%94%A8-sqlalchemy-%E5%BB%BA%E7%AB%8B%E8%B3%87%E6%96%99-%E4%B8%80-ff76ab9413a8?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff76ab9413a8</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 12:11:01 GMT</pubDate>
            <atom:updated>2024-07-23T14:48:34.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>使用 SQLAlchemy 建立資料（一）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*LWWScXhnEW9hQAFo" /></figure><p>本文將介紹兩種使用 SQLAlchemy 建立資料的方法：session.add() 和 insert()，並探討它們的運作機制與差異。</p><h3>環境設置</h3><p>首先，讓我們透過以下程式碼來建立 SQLite 資料庫和 “Road” 資料表：</p><pre>from sqlalchemy import Column, Integer, select, insert<br>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker, DeclarativeBase<br><br>class Base(DeclarativeBase):<br>    pass<br><br>class Road(Base):<br>    __tablename__ = ‘road’<br>    id = Column(Integer, primary_key=True)<br>    start = Column(Integer)<br>    end = Column(Integer)<br><br>engine = create_engine(&quot;sqlite+pysqlite:///:memory:&quot;, echo=True)<br>Base.metadata.create_all(engine)<br>Session = sessionmaker(bind=engine)</pre><p>在 <strong>create_engine</strong> 的設定中，將 <strong>echo</strong> 設為 <strong>True</strong> 可以讓我們看到 SQLAlchemy 實際執行的 SQL 語句。</p><h3>建立資料</h3><p>接下來，我們將介紹兩種建立資料的方法。</p><h3>方法一：使用 session.add()</h3><p>這個方法通過 session 的 <strong>add()</strong> 函數來建立一筆資料：</p><pre>def create():<br>    with Session() as _session:<br>        road1 = Road(start=1, end=10)<br>        _session.add(road1)<br>        _session.commit()<br>create()</pre><p>對應的 SQL 語句如下：</p><pre>INFO sqlalchemy.engine.Engine BEGIN (implicit)<br>INFO sqlalchemy.engine.Engine INSERT INTO road (start, &quot;end&quot;) VALUES (?, ?)<br>INFO sqlalchemy.engine.Engine [generated in 0.00008s] (1, 10)<br>INFO sqlalchemy.engine.Engine COMMIT</pre><p>注意，如果我們將 <strong>_session.commit()</strong> 註解掉，則不會有任何 SQL 語句發送到資料庫。<strong>這體現了「工作單元模式」的概念：修改會先在記憶體中累積，直到執行 </strong><strong>commit() 才會發送到資料庫。</strong></p><h3>方法二：使用 insert()</h3><p>另一種方式是使用 <strong>SQLAlchemy Core</strong> 的 <strong>insert()</strong> 語法：</p><pre>def create_by_statement():<br>    with Session() as _session:<br>        statement = (<br>            insert(Road)<br>            .values(start=1, end=10)<br>        )<br>        road = _session.execute(statement)<br>        _session.commit()<br><br>create_by_statement()</pre><p>實際執行的 SQL 語句與第一種方法完全相同。</p><p>但如果我們註解掉 <strong>_session.commit()</strong> 並重新執行，則會不同的資料庫互動結果：</p><pre>INFO sqlalchemy.engine.Engine BEGIN (implicit)<br>INFO sqlalchemy.engine.Engine INSERT INTO road (start, &quot;end&quot;) VALUES (?, ?)<br>INFO sqlalchemy.engine.Engine [generated in 0.00009s] (1, 10)<br>INFO sqlalchemy.engine.Engine ROLLBACK</pre><p>可以觀察到：即使沒有執行 commit()，execute() 方法仍會直接將 SQL 語句發送到資料庫。</p><p>但因為沒有後續的 commit()，這些變更不會被永久保存，而是在 session 結束時被捨棄 （rollback）。</p><h3>小結</h3><p>不論是使用 <strong>session.add()</strong> 還是 <strong>insert()</strong>，都能達到建立資料的目的。</p><p>然而，這兩種方法在將修改發送到資料庫的時間點上有所不同：使用 <strong>session.add()</strong> 會累積修改，並在 <strong>session.commit()</strong> 時一次性發送；而使用 <strong>session.execute</strong> 加上 <strong>insert()</strong> 則是每次修改後立即發送。</p><p>透過這篇文章，我們學習了如何使用 SQLAlchemy 進行基礎的資料建立操作，並理解了兩種不同方法的運作機制。希望這對想了解 SQLALchemy 的你有所幫助！</p><h3>Reference</h3><p><a href="https://docs.sqlalchemy.org/en/20/tutorial/orm_data_manipulation.html">https://docs.sqlalchemy.org/en/20/tutorial/orm_data_manipulation.html</a></p><p><a href="https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-bulk-insert-statements">https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-bulk-insert-statements</a></p><p><a href="https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.insert">https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.insert</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff76ab9413a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy Session 核心原理]]></title>
            <link>https://hot50773.medium.com/sqlalchemy-session-%E6%A0%B8%E5%BF%83%E5%8E%9F%E7%90%86-e41340e66ad8?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/e41340e66ad8</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 15:00:33 GMT</pubDate>
            <atom:updated>2024-01-16T10:51:21.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQLAlchemy Session 原理</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*LWPHnvtMORiSEAOL" /></figure><p>本文探討 SQLAlchemy Session 原理 — — 什麼是 Session？SQLAlchemy Session 如何與資料庫互動？採用什麼做法來維護資料一致性？</p><p>以下就來逐步探討吧！</p><h3>什麼是 Session?</h3><blockquote>一個 Session 代表與資料庫的一次 &quot;對話&quot;，允許您查詢和操作數據。</blockquote><p>1. Session 建立了與資料庫的對話，並代表其生命週期中所有已載入、已關聯物件的<strong>“保留區”</strong> (“holding zone”)。</p><p>2. Session 提供了一個界面，可以發出資料庫 Query，這些 Query 會回傳、修改 ORM 物件。</p><h3>Session 與資料庫的對話過程</h3><p>Session 初始時是無狀態的。</p><p>一旦<strong>發出 Query</strong>，它會從<strong>與 Session 關聯的引擎中請求一個連接（connection）</strong>，然後在該連接上建立 <strong>transaction</strong>。</p><p><strong>這個 transaction 會一直保持有效，直到 Session 被指示提交 (commit) 或回滾 (rollback)。</strong></p><h3>Session 如何與資料庫狀態保持同步</h3><p>透過以下機制，Session 能確保 ORM 物件與資料庫狀態保持同步，並提供一個高效且一致的方式來與資料庫互動。</p><ol><li><strong>身份映射 (Identity Map)</strong></li><li><strong>追踪變更 (Change Tracking)</strong></li><li><strong>自動刷新</strong></li><li><strong>分離和重新附加</strong></li><li><strong>延遲加載 (Lazy Loading)</strong></li></ol><p>下面就來逐一探討這五大機制。</p><h4>1. 身份映射 (Identity Map)</h4><blockquote>Identity Map is a mapping between Python objects and their database identities.</blockquote><p><strong>為了確保每個物件在記憶體中只有一個實例，ORM 使用身份映射來維護物件。</strong></p><p>ORM 物件本身由 Session 維護，內部有一個稱為 “身份映射” (<a href="https://docs.sqlalchemy.org/en/20/glossary.html#term-identity-map">identity map</a>)的資料結構 — 用來維護每個物件的唯一副本 (unique copies)</p><p>這種模式的優點是，對於特定資料庫 identity 的所有操作都會透明地同步到單一物件實例上。</p><h4>2. 追蹤變更 (Change Tracking)</h4><p>每當在 Python 修改屬性或集合時，這些更改會被 Session 捕捉。這允許 Session 知道哪些對象已被修改，並在需要時將這些更改寫入資料庫。</p><blockquote>SQLAlchemy 透過描述器 (Descriptor)，追蹤資料變更</blockquote><blockquote><strong>什麼是描述器 (Descriptor)？</strong></blockquote><blockquote>在 Python，<strong>描述器是具有“綁定行為” 的物件屬性 (binding behavior) </strong>。讓你能夠在讀取、變更、刪除屬性時，執行自定義的邏輯。</blockquote><blockquote><strong>描述器相關的方法是 </strong><strong>__get__()、</strong><strong>__set__() 和 </strong><strong>__delete__()</strong>。</blockquote><blockquote>如果一個物件覆寫了以上任意一個方法，那麼它就被認為是一個描述器。</blockquote><p><strong>SQLAlchemy 正是運用了以上特點，他為 ORM 添加了資料庫可用的描述器 </strong>(descriptor)。每一個描述器代表特定的資料表欄位 (column) ，或與相關類別的關係。</p><p>當 ORM 物件的屬性被修改時，這些變更就能透過描述器捕捉，並在需要時將這些變更寫入資料庫中。</p><h4>3. 自動刷新：工作單元模式 Unit of Work Pattern</h4><p>每當要查詢資料庫，或者即將提交 Transaction 之前，Session 會先將存儲在記憶體中的所有 pending changes 刷新到資料庫 (flush)。這又稱為工作單元模式。它確保了記憶體中的狀態與資料庫保持同步。</p><h4>4. 分離和重新附加 (Detachment and Re-attachment)</h4><p>你可以將 ORM 物件從一個 Session 分離 (<strong>Detach</strong>)，然後在另一個 Session 中重新附加它。當物件重新附加時，它的狀態會與資料庫同步，確保資料的一致性。</p><h4>5. 延遲載入 (Lazy Loading)</h4><p>為了效率，ORM 物件的某些屬性或關聯可能不會立即從資料庫中加載。只有當你真正訪問這些屬性時，它們才會被加載。這確保了只有真正需要的數據才會從資料庫中被加載。</p><h3>結語</h3><p>SQLAlchemy Session 的機制，讓 Python 中與資料庫的互動變得更加簡單、有條理。透過身份映射、變更追蹤、自動刷新等機制，它提供了一個穩定、靈活的方式來處理資料庫操作，同時保證了資料的一致性和應用程式的效能。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e41340e66ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy (二) — 如何使用 SQLAlchemy ORM]]></title>
            <link>https://hot50773.medium.com/sqlalchemy-orm-%E4%BA%8C-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-sqlalchemy-d0118b41c30c?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0118b41c30c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 19:35:20 GMT</pubDate>
            <atom:updated>2023-12-09T10:19:18.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*srg9H5JQoKFSLoBL" /></figure><p>繼上一篇 SQLAlchemy 簡介後，這次要來實作精簡版的 SQLAlchemy 程式範例。</p><p>實作流程如下：</p><blockquote>創建 Engine</blockquote><blockquote>定義 ORM Model</blockquote><blockquote>在目標 Database 生成資料表</blockquote><blockquote>使用 Session 操作資料</blockquote><h3>1. 創建 Engine</h3><p>首先創建 Engine，用來建立 DB 連線</p><p><strong>Engine 是什麼？</strong></p><ul><li>Engine 是連接到特定資料庫的中心來源。它提供了一個工廠和稱為<strong>連接池（Connection Pool）</strong>的儲存空間，用於管理資料庫連接。</li><li>Engine 通常作為全局物件存在。也就是說，針對特定的資料庫伺服器只會創建一次。</li></ul><pre>from sqlalchemy import create_engine<br>engine = create_engine(&quot;sqlite+pysqlite:///:memory:&quot;, echo=True)</pre><p><strong>create_engine 主要參數為一個 URL</strong> <strong>sqlite+pysqlite:///:memory:，包含了三個重點</strong>：</p><ul><li><strong>我們正在與哪種資料庫溝通？</strong> <br>在這個例子中為 sqlite</li><li><strong>我們使用哪個 DBAPI？<br></strong>Python 的 DBAPI 是 SQLAlchemy 用來與特定數據庫互動的第三方驅動。在這個例子中，我們使用的是 pysqlite，它在現代 Python 中是 SQLite 的 sqlite3 標準庫接口。</li><li><strong>我們如何定位資料庫？</strong> <br>在這個例子中為 /:memory，這是對 sqlite3 模組的指示，表明我們將使用一個<strong>僅存在於記憶體中的資料庫</strong>。這種類型的數據庫非常適合實驗，因為它不需要任何服務器，也不需要創建新檔案。</li></ul><h3>2. 宣告 ORM Model</h3><p>在 SQLAlchemy 中宣告模型（Model），建立 Python 類別與資料庫 Table 之間的映射關係。</p><pre>from sqlalchemy import Column, Intege, Text<br>from sqlalchemy.orm import DeclarativeBase<br><br>class Base(DeclarativeBase):<br>    pass<br><br>class Article(Base):<br>    __tablename__ = &#39;article&#39;<br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    title = Column(Text)<br>    content = Column(Text)<br>    view_count = Column(Integer, default=0)</pre><ul><li>透過 Model，你可以在 Python 定義資料庫的結構（例如，表、欄位、索引、關聯、約束等）。</li><li>這些用來描述資料庫結構的資訊，被稱作 DataBase MetaData。</li></ul><h3>3. 在目標 Database 創建資料表</h3><p>使用 Model 定義的資料結構和 Engine，就能針對目標 Database 生成 Table</p><pre>Base.metadata.create_all(engine)</pre><p>當你呼叫 <strong>metaData.create_all()</strong>，SQLAlchemy 會查看 metadata 中定義的所有 Table Object，並生成 SQL 語句 <strong>CREATE TABLE</strong> ，在資料庫中創建 Table。</p><p>例如以上 Model 定義後，呼叫 <strong>create_all()</strong> 會生成 SQL 如下：</p><pre><br>BEGIN<br>PRAGMA main.table_info(&quot;article&quot;)<br>PRAGMA temp.table_info(&quot;article&quot;)<br><br>CREATE TABLE article (<br>        id INTEGER NOT NULL, <br>        title TEXT, <br>        content TEXT, <br>        view_count INTEGER, <br>        PRIMARY KEY (id)<br>)<br><br>COMMIT</pre><blockquote>資料表的創建，通常會在應用程式啟動初期進行，確保必要的資料庫架構已到位。</blockquote><blockquote>如果某個 Table 在資料庫已存在，SQLAlchemy 不會再重新創建它。（default 設定）</blockquote><h3>4. 使用 Session 操作資料</h3><p>使用 Session 和 ORM 物件，就能實現資料的 CRUD</p><h4>創建資料</h4><pre>from sqlalchemy.orm import sessionmaker<br><br>Session = sessionmaker(bind=engine)<br><br>with Session() as session:<br>    welcome_article = Article(title=&#39;Hello World&#39;, content=&#39;This is my first article&#39;)<br>    announcement_article = Article(title=&#39;Important Announcement&#39;, content=&#39;This is an important announcement&#39;)<br>    session.add_all([welcome_article, announcement_article])<br>    session.commit()</pre><ul><li>sessionmaker是一個工廠函數，呼叫時會產生新的 Session 物件。</li><li>一個 <strong>Session</strong> 代表與資料庫的一次 “<strong>對話”</strong>，允許您查詢和操作數據。</li></ul><h4>更新資料</h4><pre>with Session() as session:<br>    article = session.query(Article).filter(Article.id == article_id).first()<br>    article.view_count += 1<br>    session.commit()</pre><h4>查詢</h4><pre>with Session() as session:<br>    article = session.query(Article).filter(Article.id == article_id).first()<br><br>    print(f&quot;title: {article.title}, view_count: {article.view_count}&quot;)<br>    return article<br><br># title: Hello World, view_count: 1</pre><p>以上就是一個精簡版的 SQLAlchemy 使用範例</p><p>最後附上完整程式碼</p><pre>from sqlalchemy import Column, Integer, Text<br>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker, DeclarativeBase<br><br><br>class Base(DeclarativeBase):<br>    pass<br><br><br>class Article(Base):<br>    __tablename__ = &#39;article&#39;<br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    title = Column(Text)<br>    content = Column(Text)<br>    view_count = Column(Integer, default=0)<br><br><br>engine = create_engine(&quot;sqlite+pysqlite:///:memory:&quot;, echo=True)<br><br>Base.metadata.create_all(engine)<br>Session = sessionmaker(bind=engine)<br><br><br>def insert_article():<br>    with Session() as session:<br>        welcome_article = Article(title=&#39;Hello World&#39;, content=&#39;This is my first article&#39;)<br>        announcement_article = Article(title=&#39;Important Announcement&#39;, content=&#39;This is an important announcement&#39;)<br><br>        session.add_all([welcome_article, announcement_article])<br>        session.commit()<br><br><br>def update_article_count(article_id: int):<br>    with Session() as session:<br>        article = session.query(Article).filter(Article.id == article_id).first()<br>        article.view_count += 1<br>        session.commit()<br><br><br>def get_article(article_id: int):<br>    with Session() as session:<br>        article = session.query(Article).filter(Article.id == article_id).first()<br><br>        print(f&quot;title: {article.title}, view_count: {article.view_count}&quot;)<br>        return article<br><br><br>def main():<br>    insert_article()<br>    update_article_count(article_id=1)<br>    get_article(article_id=1)<br><br><br>main()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0118b41c30c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy 簡介]]></title>
            <link>https://hot50773.medium.com/sqlalchemy-orm-%E5%85%A5%E9%96%80-ce056b914af9?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce056b914af9</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 18:21:51 GMT</pubDate>
            <atom:updated>2023-12-09T04:17:32.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*oVBT_-aozHkO5Adh" /></figure><blockquote><em>SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL</em></blockquote><p>SQLAlchemy 是一款 Python Library，用於與關聯式資料庫進行互動。</p><p>它主要提供兩大功能：</p><ol><li><strong>SQL 工具包</strong>：讓開發者能使用 Python 語法撰寫 SQL Query，與資料庫進行互動。</li><li><strong>物件關係對映（Object Relational Mapper，簡稱 ORM）</strong>：讓開發者能將 Python 物件映射到資料庫的 Table。這代表你能使用物件導向的方式去操作資料庫，例如創建、讀取、更新和刪除資料，無需直接使用 SQL 語言。</li></ol><h3>SQLAlchemy API</h3><p>SQLAlchemy 分為兩個 API 層次：<strong>Core</strong> 和 <strong>ORM</strong>，這兩者分別實現了 SQL Alchemy 的兩大功能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_90eY8M3WjgCUo27Yr3OQ.png" /></figure><h4>SQLAlchemy Core</h4><p>SQLAlchemy Core<strong> </strong>是 SQLAlchemy 作為「資料庫工具包」的基礎架構。這套 Library 的功能有：</p><ul><li>管理 DB Connection</li><li>使用 Python 程式化指令，建構 SQL 語句</li><li>與資料庫的查詢和結果互動（<strong>發送 DB Query → </strong>解讀回傳結果 → 轉換為 Python 資料結構）</li></ul><h4>SQLAlchemy ORM</h4><p>SQLAlchemy ORM 建構在 Core 的基礎之上，提供物件關係映射的功能。</p><p>ORM 的功能：</p><ul><li>能將使用者定義的 Python 類別，映射到資料表 (Database Table)</li><li>提供一個稱為 Session 的物件持久化機制</li></ul><p>ORM 還擴展了 Core 層級的 SQL 表達式語言，能根據使用者定義的物件來組合、呼叫 SQL Query。</p><h3>ORM 框架的 Pros &amp; Cons</h3><h4>優點</h4><ol><li>提高開發效率：ORM 封裝了對資料庫的操作，讓開發者可以像操作物件一樣操作資料庫，寫出來的程式也更符合物件導向的思維，因此更容易閱讀和維護。</li></ol><p>2. 可移植性：如果未來需要更換資料庫，使用 ORM 可以輕鬆移植程式碼，而不需要大量修改。</p><p>3. 安全性：ORM 可以防止 SQL 注入攻擊。</p><h4>缺點</h4><ol><li>效能問題：由於 ORM 在背後進行了大量的轉換與映射，因此效能可能會比直接使用原生 SQL 語句差一些。</li><li><strong>過度抽象</strong>：ORM 的抽象層可能隱藏了資料庫的重要細節，使開發者難以理解背後的資料庫操作。過度依賴 ORM 可能會導致開發者對 SQL 的理解不足。</li><li>針對複雜查詢的侷限性：對於一些複雜的查詢和資料操作，ORM 框架可能無法提供足夠的彈性。在這些情況下，直接使用 SQL 可能是更好的選擇。</li></ol><h3>總結</h3><p>SQLAlchemy 是一個功能強大的 Python 庫，旨在簡化與關聯式資料庫的互動。</p><p>對於標準的 CRUD 操作，SQLAlchemy ORM 可以顯著提高開發效率，因為它允許開發者以更自然的物件導向方式進行資料操作。</p><p>但如果你想執行複雜查詢，或更細緻的查詢優化，直接使用 raw SQL 也是個好選擇。</p><h4>參考資料</h4><p><a href="https://worktile.com/kb/ask/62473.html">https://worktile.com/kb/ask/62473.html</a></p><p><a href="https://www.explainthis.io/zh-hant/swe/orm-intro">https://www.explainthis.io/zh-hant/swe/orm-intro</a></p><p><a href="https://docs.sqlalchemy.org/en/20/orm/quickstart.html">https://docs.sqlalchemy.org/en/20/orm/quickstart.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce056b914af9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB  簡介]]></title>
            <link>https://hot50773.medium.com/%E5%88%9D%E8%AD%98-mongodb-%E7%B0%A1%E4%BB%8B-57a809ef5d68?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a809ef5d68</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 11:33:05 GMT</pubDate>
            <atom:updated>2026-06-21T15:57:55.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>MongoDB 簡介</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sfN0oqKnznlOlAP1.png" /></figure><h3>什麼是 MongoDB?</h3><p>MongoDB 是一個文檔導向的資料庫管理系統，由 C++ 語言編寫。他是目前最流行的 NoSQL 資料庫之一，並且完全開源。</p><p>MongoDB 提出文檔（Document）, 集合（Collection） 的概念。如果要用關聯式資料庫的觀念來理解的話：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*XsRo67ExsnDehWlyaorn3A.png" /></figure><h3>MongoDB 的特色</h3><ul><li>物件導向：使用 BSON 作為資料模型結構 (類似 JSON 格式)</li><li>更靈活的資料儲存方式：沒有固定的 Schema，且能儲存多層級的資料。</li><li>即時查詢能力：保留傳統的索引 (Index) 功能 （底層是 B-Tree）</li><li>分散式儲存： 支援多個儲存引擎，能將資料分散其他伺服器，共同分擔。</li></ul><h3>Collection (集合)</h3><p><strong>Collection 是一個 MongoDB document 的群組。相當於關聯式資料庫的 Table。</strong></p><h4>可以不事先定義欄位 <strong>(Schema-Free)</strong></h4><p>一般的關連式資料庫，開 Table 必須定義欄位 (大小、型別、名稱等)。<br> 但 Collection 可以不用事先定義，每筆document可以有不等數量的欄位，而存在同一個collection內。</p><h3>Document (文檔)</h3><ul><li>一個 Document 相當於資料表中的一筆紀錄</li><li>他的基本結構就是 <strong>key-value pair</strong></li></ul><h4>Document 範例</h4><pre>{<br>   _id: ObjectId(7df78ad8902c)<br>   title: &#39;MongoDB Overview&#39;, <br>   description: &#39;MongoDB is no sql database&#39;,<br>   by: &#39;tutorials point&#39;,<br>   url: &#39;http://www.tutorialspoint.com&#39;,<br>   tags: [&#39;mongodb&#39;, &#39;database&#39;, &#39;NoSQL&#39;],<br>   likes: 100, <br>   comments: [	<br>      {<br>         user:&#39;user1&#39;,<br>         message: &#39;My first comment&#39;,<br>         dateCreated: new Date(2011,1,20,2,15),<br>         like: 0 <br>      },<br>      {<br>         user:&#39;user2&#39;,<br>         message: &#39;My second comments&#39;,<br>         dateCreated: new Date(2011,1,25,7,45),<br>         like: 5<br>      }<br>   ]<br>}</pre><h3>_id</h3><p><strong>每一個 Doument 必定會有一個最基本的特殊欄位 “_id”</strong></p><ul><li>在所屬的 Collection 底下，_id 為唯一值。</li><li>_id 長度為 12，由 16 進位數字組成</li><li>其結構為 [timestamp][machine_id][process_id][increment]</li><li>timestamp: 當前時間 (4byte)</li><li>machine_id: 機器 id (3byte)</li><li>process_id: 伺服器的 process id (2 byte)</li><li>increment number: 簡單的遞增數字 (3byte)</li></ul><h3>參考資源：</h3><p><a href="https://kknews.cc/zh-tw/code/g954yvm.html">https://kknews.cc/zh-tw/code/g954yvm.html</a><br><a href="https://www.tutorialspoint.com/mongodb/index.htm">https://www.tutorialspoint.com/mongodb/index.htm</a><br><a href="https://kknews.cc/code/lqneyng.html">https://kknews.cc/code/lqneyng.html</a><br><a href="https://dotblogs.com.tw/sungnoone/2012/01/11/65274">https://dotblogs.com.tw/sungnoone/2012/01/11/65274</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a809ef5d68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS — 在 require 使用絕對路徑]]></title>
            <link>https://hot50773.medium.com/nodejs-%E5%9C%A8-require-%E4%BD%BF%E7%94%A8%E7%B5%95%E5%B0%8D%E8%B7%AF%E5%BE%91-b6827746a24c?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6827746a24c</guid>
            <category><![CDATA[absolute-path]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 07:41:09 GMT</pubDate>
            <atom:updated>2021-06-17T07:41:09.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>NodeJS — 在 require 使用絕對路徑</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYbux-1ZjXdEc9MSEBVoNw.png" /></figure><p>在寫 NodeJS 應用程式時，常會遇到想在 A 模組的程式，引用 B 模組或是上層資料夾的檔案，如果使用相對路徑的寫法require(&#39;./../../lib/module-b/b&#39;)，會導致引用路徑變得很複雜。</p><p>假設專案資料夾結構如下：</p><pre>.<br>├── app.js<br>├── folder-a<br>│   └── path-to<br>│       └── a.js<br>└── lib<br>    └── module-b<br>        └── b.js</pre><p>你可以看到這裡有三支檔案</p><ol><li>app.js</li><li>folder-a/path-to/a.js</li><li>lib/module-b/b.js</li></ol><p>若我想在 a.js 引用 b.js 這支檔案，語法會變成</p><pre>// folder-a/path-to/a.js</pre><pre>require(&#39;./../../lib/module-b/b&#39;)</pre><p>以上是使用 <strong>”相對路徑” </strong>的做法，可以看到有很多 ./../ 字串，會導致兩個問題</p><ol><li>可讀性差：<br>工程師閱讀程式碼時，會很困惑（OS: 現在到底是引用哪一層資料夾的檔案)。<br>為了確認檔案位置，還要跟著引用的資料夾層數，一層層的數一遍，數完腦袋也差不多暈了ＸＤ。</li><li>可維護性差：<br>假設你想把 a 檔案搬到不同資料夾時，require 的路徑就要跟著改寫。就算你是搬動 b.js 檔案，require 路徑還是要改。<br>因為這兩隻檔案的路徑有很高的相依性，所以搬動時容易導致程式碼出錯。</li></ol><p>要修正這個問題，最好的方式就是<strong>改成”絕對路徑”的寫法</strong>，以下是幾種可行的做法</p><h4>1. 將資料夾註冊成 workspace</h4><p>在 module-b 資料夾，新增 package.json 檔，裡面的 &quot;name&quot; 設定為 &quot;workspace-b&quot; (自己取名)</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;workspace-b&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><p>接著，在專案根目錄的 package.json</p><ul><li>新增 &quot;workspaces&quot;，並加入 &quot;lib/module-b&quot; (你想引用的資料夾路徑)</li><li>將 &quot;private&quot; 設為 true</li></ul><pre>// package.json<br>{<br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: [&quot;lib/module-b&quot;]<br>}</pre><p>安裝：回到專案根目錄，執行 yarn install 或 npm install。安裝完成後，會發現 node_modules 多出了 workspace-b 這個資料夾</p><p>這時，再回去a.js，把引用的方式改掉，就完成了！</p><pre>// folder-a/path-to/a.js</pre><pre>require(&#39;workspace-b/b&#39;)</pre><h4>2. 將資料夾註冊成 dependency 模組</h4><p>這個做法跟上面 workspace 類似，只是寫法不同</p><p>先在 module-b 資料夾內，新增一個 package.json 檔，取名為 &quot;workspace-b&quot;</p><pre>// package.json</pre><pre>{<br>  &quot;name&quot;: &quot;workspace-b&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><p>加入 dependency：在專案根目錄的 package.json</p><ul><li>將 &quot;private&quot; 設為 true</li><li>在 teminal 執行 yarn add workspace-b@file:lib/module-b<br>或者你也可在 package.json 的 dependencies 自己手動加入：&quot;workspace-b&quot;: &quot;file:lib/module-b&quot;之後，執行 yarn install</li></ul><pre>// package.json<br>{<br>  &quot;private&quot;: true,<br>  &quot;dependencies&quot;: {<br>    &quot;workspace-b&quot;: &quot;file:lib/module-b&quot;,<br>  }<br>}</pre><p>這個做法也會將 lib/module-b 註冊為一個模組，並加入至 node_modules 內</p><p>最後同樣修改 a.js，就完成了</p><pre>// folder-a/path-to/a.js<br>require(&#39;workspace-b/b&#39;)</pre><h3>3. 使用套件</h3><p>以下套件都是在解決相對路徑的問題，讓你在引用資源時，能使用絕對路徑。可以自己玩玩看！</p><ul><li><a href="https://www.npmjs.com/package/module-alias">module-alias</a></li><li><a href="https://www.npmjs.com/package/sexy-require">sexy-require</a></li><li><a href="https://www.npmjs.com/package/undot">undot</a></li><li><a href="https://www.npmjs.com/package/rfr">node-rfr</a></li><li><a href="https://github.com/patrick-steele-idem/app-module-path-node">app-module-path-node</a></li></ul><h3>Reference</h3><ul><li><a href="https://stackoverflow.com/questions/10860244/how-to-make-node-js-require-absolute-instead-of-relative/26163910">stackoverflow discussion</a></li><li><a href="https://docs.npmjs.com/cli/v7/using-npm/workspaces">using npm workspaces</a></li><li><a href="https://classic.yarnpkg.com/en/docs/workspaces/">yarn workspaces</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6827746a24c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[筆記] JavaScript Error 物件]]></title>
            <link>https://hot50773.medium.com/%E7%AD%86%E8%A8%98-javascript-error-%E7%89%A9%E4%BB%B6-c3b02cd6706c?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b02cd6706c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 16:43:01 GMT</pubDate>
            <atom:updated>2021-07-02T12:51:52.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>[筆記] JavaScript Error in Node.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lUzFH6PdHAkV9Ohc.png" /></figure><h3>大綱</h3><h4><strong>Node.js 的錯誤類型</strong></h4><ol><li>標準 JavaScript 錯誤</li><li>系統錯誤</li><li>自定義錯誤</li><li>特殊錯誤</li></ol><h4><strong>Error Class API</strong></h4><ol><li>介紹</li><li>API 用法</li></ol><h3>Node.js 錯誤類型</h3><p>Node.js 執行的應用程式會遇到四類錯誤：</p><h4><strong>1. 標準 JavaScript 錯誤</strong></h4><ul><li>&lt;EvalError&gt;</li><li>&lt;SyntaxError&gt;</li><li>&lt;RangeError&gt;</li><li>&lt;ReferenceError&gt;</li><li>&lt;TypeError&gt;</li><li>&lt;URIError&gt;</li></ul><h4><strong>2. 系統錯誤</strong></h4><p>由底層作業系統觸發 (ex: 嘗試打開不存在的文件)</p><h4><strong>3. 自定義錯誤</strong></h4><p>呈現給使用者看的錯誤訊息</p><h4><strong>4. 特殊錯誤</strong></h4><p>AssertionErrors，在 Node.js 檢測到不應該發生的異常邏輯時觸發。通常由assert模組引發。</p><h3>Error Class API</h3><ul><li>JavaScript 內建&lt;Error&gt;類別</li><li>Node.js 引發的所有 JavaScript 和系統錯誤，都是 Error 類別的實例，或是繼承自它。</li><li>它會捕獲 “stack trace” (堆疊追蹤)，其中說明了程式碼中出錯的位置，並提供錯誤的文字描述</li></ul><h3>用法</h3><h4>new Error(message)</h4><p>創建一個新Error 物件，並透過 error.message 屬性設定錯誤訊息文字。</p><h4>Error.captureStackTrace (targetObject, constructorOpt)</h4><ul><li>會在<strong>第一個參數</strong> targetObject 上，建立一個 .stack 屬性</li><li>訪問該屬性時，會回傳一個字串，表示 Error.captureStackTrace() 被呼叫時的程式碼位置</li></ul><pre>const myObject = {};<br>Error.captureStackTrace(myObject);<br>myObject.stack;</pre><pre>// Similar to `new Error().stack`</pre><p><strong>第二個參數 </strong><strong>constructorOpt</strong></p><ul><li>為可選參數(optional)，接受一個函數作為輸入值</li><li>若使用它，constructorOpt 以上（包含他自己）的所有幀，將在 stace trace（堆疊追蹤） 中被省略</li><li>這個參數對於向用戶隱藏錯誤生成的細節很有用。</li></ul><pre>function MyError() {<br>  Error.captureStackTrace(this, MyError);<br>}</pre><pre>// Without passing MyError to captureStackTrace, the MyError<br>// frame would show up in the .stack property. By passing<br>// the constructor, we omit that frame, and retain all frames below it.<br>new MyError().stack;</pre><h4>Error.stackTraceLimit</h4><p>指定堆疊追蹤（stack trace）收集的堆疊幀數，預設為 10</p><h4>error.code</h4><ul><li>error.code 屬性是一個標籤（字串），用於識別錯誤類型。</li><li>error.code 是識別錯誤的最穩定方法。它只會在 Node.js 的主要版本間發生變化。（<a href="https://nodejs.org/api/errors.html#nodejs-error-codes">請參見 Node.js 錯誤代碼</a>）</li></ul><h4>error.message</h4><p>error.message 屬性是一個描述字串，在呼叫 new Error(message) 時設定完成</p><pre>new Error(‘my error msg’)</pre><pre>// Output &quot;Error: my error msg&quot;</pre><h4>error.stack</h4><p>error.stack 屬性是一個字串，描述程式碼中 Error 實例化的位置。</p><pre>Error: Things keep happening!<br>   at /home/gbusey/file.js:525:2<br>   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)<br>   at Actor.&lt;anonymous&gt; (/home/gbusey/actors.js:400:8)<br>   at increaseSynergy (/home/gbusey/actors.js:701:6)</pre><p>第一行的格式為&lt;error class name&gt;: &lt;error message&gt;</p><h4>小結：</h4><p>這篇文章介紹了 Node.js 中會出現的 Error 類型，以及基本 Error Class 會用到的 API，其他更詳盡的介紹請參考</p><p><a href="https://nodejs.org/api/errors.html#errors_errors">https://nodejs.org/api/errors.html#errors_errors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b02cd6706c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git 情境筆記— 為本地 git 專案，設定對應的[遠端儲存庫]]]></title>
            <link>https://hot50773.medium.com/git-%E6%83%85%E5%A2%83%E7%AD%86%E8%A8%98-%E7%82%BA%E6%9C%AC%E5%9C%B0-git-%E5%B0%88%E6%A1%88-%E8%A8%AD%E5%AE%9A%E5%B0%8D%E6%87%89%E7%9A%84-%E9%81%A0%E7%AB%AF%E5%84%B2%E5%AD%98%E5%BA%AB-e88a6ba63b95?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/e88a6ba63b95</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[w3hexschool]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 10:38:37 GMT</pubDate>
            <atom:updated>2021-02-15T13:37:26.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*JqqAcHB2nzVgq3bV" /></figure><h3>問題情境</h3><p>我在<strong>『本機端』已建立好一個 Git 儲存庫</strong>，但在遠端 (EX: Github上)，還沒有對應的儲存庫。</p><p>此時該如何『建立一個遠端儲存庫』，並『將資料同步上去』？</p><h3>解法</h3><h4>1. 在 github 創立一個 repository （遠端儲存庫）</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7J_TrOjYsx3p1Pd2z48ag.png" /></figure><h4>2. 在本機，設定對應的「遠端儲存庫」</h4><p>設定預設的遠端節點</p><p>$ git remote add origin https://github.com/your-url-path</p><h4><strong><em>語法筆記</em></strong></h4><blockquote>git remote :跟遠端有關的操作。</blockquote><blockquote>add :加入一個遠端的節點。</blockquote><blockquote>origin: 這裡的<strong> origin</strong> 是一個「代名詞」，他會指向 <strong>後面那串 GitHub 伺服器的位置</strong>。(慣例上，遠端的節點預設會用 origin 這個名字。)</blockquote><h4>3. 將本機的 git 儲存的檔案，推送至 GitHub 遠端</h4><p>因為現在 GitHub 預設的主分支叫做 “main”，因此我們要先將本地端的主分支改名為 main 在推送上去</p><ul><li><strong>將目前分支(主分支)重新命名為 “main”<br></strong>$ git branch -M main<br> (若 main 分支已存在，那個原本的 main 分支會被強制覆寫掉。)</li><li><strong>將本機 main 分支的內容，推送至遠端 (GitHub) 的 main。</strong><br>＄git push -u origin main</li></ul><h4>語法原理</h4><h4>$ git push -u origin main</h4><p>在 origin 那個遠端 Server 上:</p><ul><li>如果 main不存在，就建立一個叫做 main的同名分支。</li><li>如果 main 分支本來就存在，便會移動遠端 Server 上 ，main 分支的位置，使它指到目前最新的進度上。</li></ul><p><strong>“-u” </strong>代表『 <strong>upstream (上游)</strong>』</p><p>在 Git 裡，<strong><em>每個分支可以設定唯一的「上游」</em></strong>，它會<strong><em>指向並追蹤（track）某個分支</em></strong>。</p><p>(通常 upstream 會是遠端 Server 的某個分支，但其實要設定在本地端的其它分支也可以。)</p><h4>參考來源</h4><p><a href="https://gitbook.tw/chapters/github/push-to-github.html">高見龍 </a><a href="https://gitbook.tw/">為你自己學 Git</a> <a href="https://gitbook.tw/chapters/github/push-to-github.html">（https://gitbook.tw/chapters/github/push-to-github.html）</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e88a6ba63b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用 JavaScript 解 LeetCode — Longest Substring Without Repeating Characters]]></title>
            <link>https://hot50773.medium.com/%E7%94%A8-javascript-%E8%A7%A3-leetcode-longest-substring-without-repeating-characters-a8537bfed52a?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8537bfed52a</guid>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[w3hexschool]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 17:06:29 GMT</pubDate>
            <atom:updated>2020-11-01T17:22:27.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>用 JavaScript 解 LeetCode — Longest Substring Without Repeating Characters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*D2DKAySxAIT2AHf1.png" /></figure><h3>題目</h3><p><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/">這次的 LeetCode 題目是「找出沒有重複字母的最長子字串」</a>，難度為 medium。</p><h3>官方範例</h3><ul><li>輸入值: “abcabcbb”</li><li>輸出值: 3</li><li>說明: 最長的「子字串」為 “abc”, 長度是 3</li></ul><h3>關鍵點</h3><ol><li>如何有效找出所有可能的「子字串」</li><li>計算「最大子字串」的長度</li><li>判斷是否有「重複字母」</li></ol><h3>解題思路</h3><h4>1. Sliding Window 滑動視窗演算法</h4><p>我使用 <strong>Sliding Window 演算法</strong>，來搜索出所有「符合條件的子字串」。</p><blockquote><strong>window (視窗)</strong> 在此是指 Input 字串中的一段<strong>範圍</strong> (子字串)</blockquote><blockquote>通常<strong>用 start index 和 end index 兩個索引值，來記錄視窗的邊界</strong>。</blockquote><p>目的：盡可能擴展視窗的大小，使「字母不重複」的「子字串」，範圍越長越好。</p><p>我們先從「第一個字母」開始 (start index = 0; end index = 0)</p><blockquote>i. 擴展視窗的「右邊界」 (end index++)</blockquote><blockquote>當右邊界擴展到出現「重複字母」時，停下來，計算先前那段「沒有重複字母」的視窗長度，儲存起來</blockquote><blockquote>ii.接著，將視窗「左邊界」向右收縮 (start index++)，直到裡面沒有重複字母。</blockquote><blockquote>iii. 重複 i. ii. 步驟，直到視窗無法再向右滑動 (end index 已到底)，表示我們已搜索完所有「字母不重複的子字串」。</blockquote><h4>2. 計算「最大子字串」的長度</h4><ul><li>定義一個變數 maxLength</li><li>把所有「字母不重複的子字串」的長度 (前面步驟 i 的計算結果) ，和 maxLength 比較</li><li>取兩者較大的那個，更新至 maxLength</li></ul><h4>3. 使用 Set 儲存不重複的字母</h4><ul><li><strong>Set (不重複集合)</strong> 可以用來儲存「當前子字串」包含的所有字母。</li><li>假設有一個curSet 的集合，儲存了當前視窗內所有字母。</li><li><strong>當我們拿到一個新的字母 </strong><strong>char，想判斷它是否為重複字母</strong>，用 curSet.has(char) 就能辦到。</li></ul><h3>舉例說明</h3><p>以 <strong>Input String: </strong><strong>pwwkew</strong> 為例，假設 <em>startIdx</em> 和 <em>endIdx</em> 分別為視窗的兩側邊界</p><h4>endIdx = 0</h4><p><strong><em>‘p’</em></strong><em>wwkew</em><br> 目前子字串：p，視窗邊界 [startIdx, endIdx] = [0, 0]</p><h4>endIdx = 1</h4><p><em>p</em><strong><em>‘w’</em></strong><em>wkew</em><br> 目前子字串：pw，視窗邊界 [startIdx, endIdx] = [0, 1]</p><h4>endIdx = 2</h4><p>pw’<strong>w’</strong>kew<br>目前子字串：pww -&gt;<strong>有重複字元</strong>， [startIdx, endIdx] = [0, 2]</p><ul><li><strong>更新 maxLength</strong><br> 將先前「合格子字串」(pw) 的長度記錄下來：maxLength = 2</li><li><strong>視窗左邊界向右收縮</strong><br> 從視窗的最前面開始刪除字母，直到沒有重複字母為止：<br>- <strong>刪除 p</strong><br> 目前子字串：ww，視窗邊界 [startIdx, endIdx] = [1, 2]<br>-<em> </em><strong>刪除 w</strong><br> 目前子字串：w （沒有重複字母），視窗邊界 [startIdx, endIdx] = [2, 2]</li></ul><h4>endIdx = 3</h4><p><em>pww’</em><strong><em>k’</em></strong><em>ew</em><br> 目前子字串：wk， [startIdx, endIdx] = [2, 3]</p><h4>endIdx = 4</h4><p><em>pwwk’</em><strong><em>e’</em></strong><em>w</em><br> 目前子字串：wke， [startIdx, endIdx] = [2, 4]</p><h4>endIdx = 5</h4><p><em>pwwke’</em><strong><em>w’</em></strong><br> 目前子字串：wkew -&gt; <em>有重複字母</em>， [startIdx, endIdx] = [2, 5]。</p><ul><li><strong>更新 <em>maxLength</em></strong><br> 將先前「合格子字串」(wke) 的長度記錄下來：3。我們發現他比<em>maxLength </em>還大。因此<strong>更新 maxLength 為 3</strong></li><li><strong>視窗左邊界向右收縮</strong><br> 從子字串 wkew 的最前面開始刪除字母，直到字串沒有重複字母為止：<br>- <strong>刪除 w</strong><br> 目前子字串：kew -&gt; 沒有重複字母了，更新視窗邊界 [startIdx, endIdx] = [3, 5]</li></ul><h4>此時視窗已滑動至最右側 (endIdx = 5)，搜索完畢</h4><ul><li><em>得出「字母不重複的子字串」，最長為 3 (</em><em>maxLength)</em></li></ul><h3>程式碼</h3><pre>function lengthOfLongestSubstring(s) {<br>  var startIdx = 0<br>  var endIdx = 0<br>  var maxLength = 0<br>  <br>  var curSet = new Set()<br><br>  for (let endIdx = 0; endIdx &lt; s.length; endIdx++) {<br>    if (curSet.has(s[endIdx])) {<br>      var prevEndIdx = Math.max(endIdx - 1, 0)<br>      maxLength = Math.max(prevEndIdx -  startIdx + 1, maxLength)<br>      <br>      while (s[startIdx] !== s[endIdx]) {<br>        // 視窗左邊界向右收縮，更新 curSet<br>        curSet.delete(s[startIdx++])<br>      }<br><br>      startIdx++  // 左邊界已指到重複字母的位置，往右再收縮一格<br>    } else {<br>      curSet.add(s[endIdx])<br>    }<br><br>    if (endIdx === (s.length - 1)) {<br>      maxLength = Math.max(endIdx - startIdx + 1, maxLength)<br>    }<br>  }<br><br>  return maxLength<br>};</pre><h3>Reference</h3><p><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/">https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/</a></p><p><a href="https://iter01.com/155481.html">https://iter01.com/155481.html</a></p><p><a href="https://ithelp.ithome.com.tw/articles/10185006">https://ithelp.ithome.com.tw/articles/10185006</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8537bfed52a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用 JavaScript 解 LeetCode —  4 Sum II]]></title>
            <link>https://hot50773.medium.com/%E7%94%A8-javascript-%E8%A7%A3-leetcode-4-sum-ii-5cf33fde16eb?source=rss-9bea08323a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf33fde16eb</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[w3hexschool]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Mindy Huang]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 10:22:15 GMT</pubDate>
            <atom:updated>2020-07-22T10:22:15.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>用 JavaScript 解 LeetCode — 4 Sum II</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tuhFa1joPLOVfQYsctNkgg.png" /></figure><p>這次要解的 <a href="https://leetcode.com/problems/4sum-ii/submissions/"><strong>LeetCode 題目</strong></a>，難度為 <strong>medium</strong>，一起來看看吧！</p><h3>題目</h3><p>給定 A, B, C, D 四個陣列，滿足以下條件：</p><ul><li>陣列長度皆為 N (0 ≤ N ≤ 500)</li><li>陣列元素為整數，範圍介於 -228 ~ 227。</li></ul><p>請找出：有幾組 <strong>(i, j, k, l) </strong>的組合，使得 <strong>A[i] + B[j] + C[k] + D[l]</strong> 等於 <strong>0</strong>。</p><pre>/**<br> * <a href="http://twitter.com/param">@param</a> {number[]} A<br> * <a href="http://twitter.com/param">@param</a> {number[]} B<br> * <a href="http://twitter.com/param">@param</a> {number[]} C<br> * <a href="http://twitter.com/param">@param</a> {number[]} D<br> * <a href="http://twitter.com/return">@return</a> {number}<br> */<br>var fourSumCount = function(A, B, C, D) {<br>  // Your Answer Here<br>};</pre><h3>官方範例</h3><h4>Input:</h4><p>A = [ 1, 2]<br>B = [-2,-1]<br>C = [-1, 2]<br>D = [ 0, 2]</p><h4>Output:</h4><p>2</p><h4>範例解說：</h4><p>從上述 Input 中，我們能找到兩個組合：</p><ol><li>(0, 0, 0, 1) -&gt; A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0</li><li>(1, 1, 0, 0) -&gt; A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0</li></ol><p>因此答案為 2。</p><h3>實際解題思路</h3><h4>版本 1：for 迴圈，作地毯式搜索</h4><p>這題最無腦的作法就是：直接用 4 個 for 迴圈做地毯式搜索，找出所有相加為 0 的可能性。</p><p>此做法的時間複雜度為 <strong>O(n⁴)，</strong>因為速度太慢，所以提交的結果：不通過 XD (Time Exceeded)</p><pre>var fourSumCount = function(A, B, C, D) {<br>  var i, j, k, l, length, count<br>  length = A.length<br>  count = 0<br>  <br>    for (i = 0; i &lt; length; i += 1) {<br>      for (j = 0; j &lt; length; j+= 1) {<br>        for (k = 0; k &lt; length; k += 1) {<br>          for (l = 0; l &lt; length; k += 1) {<br>            if ((A[i] + B[j] + C[k] + D[l]) === 0) count++ <br>          }<br>        }<br>      }<br>    }<br>    <br>  return count<br>};</pre><h4>版本二 (最終解法)：</h4><p>上一版的問題是時間複雜度太高（4 層 for 迴圈），因此這裡我們先將 4 Sum 問題拆成 Two Sum 問題看待：</p><p>1. 將 A, B 中的元素兩兩相加，將相加後的「和」存進 X</p><p>2. 將 C, D 中的元素兩兩相加，將相加後的「和」存進 Y</p><p>3. 找出 所有 (i, j) 的組合，使得 X[i] + Y [j] = 0，並統計組合的數量</p><p>X 和 Y 可以用 Array 的方式儲存，但此做法的時間複雜度依然為 <strong>O(n⁴)，並沒有比較快。</strong></p><p>因此我們調整一下想法：</p><ul><li>將 X, Y 內「和」重複的部分，合併在一起</li><li>將 「和」存成 key，「出現次數」存成 value，放進 Map 。</li></ul><p>最後再比較 Map X 和 Map Y 中的 key：</p><ul><li>從 Map X 取出 key (令之為 x)</li><li>搜尋 Map Y 中是否存在 key (令之為 y)，使得 x = -y，如果有，表示這是我們要找的組合，計算它的出現次數。</li><li>最後把計算出的次數加總起來，就是我們要的結果了。</li></ul><blockquote><strong>Q：為何要使用 Map 存資料？</strong></blockquote><blockquote>用 Map 儲存資料的好處是：Map <strong>搜尋元素</strong>的速度遠比「線性搜尋」快很多，因此在能<strong>有效降低時間複雜度</strong></blockquote><h4>程式碼</h4><pre>var fourSumCount = function(A, B, C, D) {<br> <br> var i, j, k, l, length<br> length = A.length<br> <br> var count = 0<br> <br> function CountTwoSum (x, y, len) {<br>   var Counts = new Map()<br>   var sum, prevCount<br> <br>   for (i = 0; i &lt; len; i += 1) {<br>     for (j = 0; j &lt; len; j+= 1) {<br>       sum = x[i] + y[j]<br> <br>       prevCount = Counts.get(sum)<br>       Counts.set(sum, prevCount ? prevCount + 1 : 1)<br>     }<br>   }<br> <br>   return Counts<br> }<br> <br> var CountAB = CountTwoSum(A, B, length)<br> var CountCD = CountTwoSum(C, D, length)<br> <br> <br> CountAB.forEach((val, key) =&gt; {<br>   let addCount = CountCD.get(-key) ? CountCD.get(-key) * val : 0<br>   if (addCount) count += addCount<br> })<br> <br> return count<br>};</pre><ul><li>提交結果：通過</li></ul><h4>Reference</h4><ul><li>題目：<a href="https://leetcode.com/problems/4sum-ii/submissions/">https://leetcode.com/problems/4sum-ii/submissions/</a></li><li>觀摩的程式碼：<a href="https://leetcode.com/problems/4sum-ii/discuss/260070/Javascript-solution-%3A0">https://leetcode.com/problems/4sum-ii/discuss/260070/Javascript-solution-%3A0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf33fde16eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>