<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Konrad&#39;s Blog</title>
<link>https://kpatucha.github.io/</link>
<atom:link href="https://kpatucha.github.io/index.xml" rel="self" type="application/rss+xml"/>
<description>Konrad Patucha&#39;s Blog</description>
<generator>quarto-1.8.27</generator>
<lastBuildDate>Sun, 07 Jun 2026 22:00:00 GMT</lastBuildDate>
<item>
  <title>SQL in Jupyter Notebook (JupySQL + VS Code + Jupyter Notebook)</title>
  <dc:creator>Konrad Patucha</dc:creator>
  <link>https://kpatucha.github.io/posts/JupySQL/</link>
  <description><![CDATA[ 





<section id="motivation" class="level1">
<h1>Motivation</h1>
<p>As a Data Scientist I often work with SQL and Python. I wanted to find a way to blend work with both of these environments seamlessly. I wanted to avoid switching between tools, because I often need to query a database and transfer the result into Python for further processing. Here I present the setup I came up with for VS Code.</p>
</section>
<section id="tldr" class="level1">
<h1>TL;DR</h1>
<ol type="1">
<li><p>Connect to the database using one of the VS Code extensions</p>
<ul>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-mssql.mssql">SQL Server (mssql) extension</a></li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-ossdata.vscode-pgsql">PostgreSQL extension</a> by Microsoft</li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=cweijan.vscode-postgresql-client2">PostgreSQL extension</a> by Database Client (supports other databases like Oracle, DuckDB etc.)</li>
</ul></li>
<li><p>Install <a href="https://jupysql.readthedocs.io/en/latest/quick-start.html">JupySQL</a></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install jupysql</span></code></pre></div></div></li>
<li><p>Create <a href="https://docs.sqlalchemy.org/en/20/core/connections.html#module-sqlalchemy.engine">SQLAlchemy engine</a> and assign it to <code>engine</code> variable</p></li>
<li><p>Load JupySQL magics and connect using <code>engine</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>load_ext sql</span>
<span id="cb2-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>sql engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>alias my_db</span></code></pre></div></div></li>
<li><p>In the cell you want to write SQL, change cell language to SQL (<code>Ctrl + K, M</code> by default)</p></li>
<li><p>Make sure the cell is connected to the database (active connection is visible at the top of the SQL cell) <img src="https://kpatucha.github.io/posts/JupySQL/cell_connect.png" class="img-fluid" alt="Connect cell"></p></li>
<li><p>Put <code>%%sql</code> magic at the top of the SQL cell</p></li>
<li><p>Write your SQL and enjoy SQL IntelliSense (context aware autocomplete), SQL formatting and work with <a href="https://jupysql.readthedocs.io/en/latest/integrations/pandas.html">Pandas DataFrames</a></p></li>
<li><p>???</p></li>
<li><p>Profit!</p></li>
</ol>
</section>
<section id="requirements" class="level1">
<h1>Requirements</h1>
<div class="tabset-margin-container"></div><div class="panel-tabset" data-group="db_type">
<ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" id="tabset-1-1-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-1" aria-controls="tabset-1-1" aria-selected="true" href="">SQL Server</a></li><li class="nav-item"><a class="nav-link" id="tabset-1-2-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-2" aria-controls="tabset-1-2" aria-selected="false" href="">PostgreSQL</a></li><li class="nav-item"><a class="nav-link" id="tabset-1-3-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-3" aria-controls="tabset-1-3" aria-selected="false" href="">Oracle and others</a></li></ul>
<div class="tab-content" data-group="db_type">
<div id="tabset-1-1" class="tab-pane active" aria-labelledby="tabset-1-1-tab">
<ul>
<li><p>VS Code (I used version 1.122.1)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">Jupyter extension</a> (and other dependencies like Python extensions etc.)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=ms-mssql.mssql">SQL Server (mssql) extension</a> <sup>1</sup></p></li>
<li><p><a href="https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver17">ODBC drivers for SQL Server</a> - often preinstalled in the system</p></li>
<li><p>Python packages</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install jupysql pandas ipykernel pyodbc</span></code></pre></div></div></li>
</ul>
</div>
<div id="tabset-1-2" class="tab-pane" aria-labelledby="tabset-1-2-tab">
<ul>
<li><p>VS Code (I used version 1.122.1)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">Jupyter extension</a> (and other dependencies like Python extensions etc.)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=ms-ossdata.vscode-pgsql">PostgreSQL extension</a> - this one is by Microsoft. <a href="https://marketplace.visualstudio.com/items?itemName=cweijan.vscode-postgresql-client2">PostgreSQL extension</a> by Database Client also works.</p></li>
<li><p>Python packages</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install jupysql pandas ipykernel <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"psycopg[binary]"</span></span></code></pre></div></div></li>
</ul>
</div>
<div id="tabset-1-3" class="tab-pane" aria-labelledby="tabset-1-3-tab">
<ul>
<li><p>VS Code (I used version 1.122.1)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">Jupyter extension</a> (and other dependencies like Python extensions etc.)</p></li>
<li><p><a href="https://marketplace.visualstudio.com/items?itemName=cweijan.vscode-postgresql-client2">PostgreSQL extension</a> by Database Client (only 3 configured connections in free tier, but supports multiple database types)<sup>2</sup></p></li>
<li><p>Python packages</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install jupysql pandas ipykernel</span>
<span id="cb5-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install oracledb <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># or other relevant database driver</span></span></code></pre></div></div></li>
</ul>
</div>
</div>
</div>
</section>
<section id="connect-to-the-database" class="level1">
<h1>Connect to the database</h1>
<section id="vs-code-extension" class="level2">
<h2 class="anchored" data-anchor-id="vs-code-extension">VS Code extension</h2>
<p>Establish connection to the database in your VS Code extension</p>
<div class="tabset-margin-container"></div><div class="panel-tabset" data-group="db_type">
<ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" id="tabset-2-1-tab" data-bs-toggle="tab" data-bs-target="#tabset-2-1" aria-controls="tabset-2-1" aria-selected="true" href="">SQL Server</a></li><li class="nav-item"><a class="nav-link" id="tabset-2-2-tab" data-bs-toggle="tab" data-bs-target="#tabset-2-2" aria-controls="tabset-2-2" aria-selected="false" href="">PostgreSQL</a></li><li class="nav-item"><a class="nav-link" id="tabset-2-3-tab" data-bs-toggle="tab" data-bs-target="#tabset-2-3" aria-controls="tabset-2-3" aria-selected="false" href="">Oracle and others</a></li></ul>
<div class="tab-content" data-group="db_type">
<div id="tabset-2-1" class="tab-pane active" aria-labelledby="tabset-2-1-tab">
<p>To test SQL Server I used <a href="https://hub.docker.com/layers/chriseaton/adventureworks/latest/images/sha256-aef97e8fb775dc6d19674a97979d17b7ae46ac634a49246dfd85f1b101bfae5c">this</a> docker image by Chris Eaton with AdventureWorks database prepopulated. <img src="https://kpatucha.github.io/posts/JupySQL/mssql_ext_connect.png" class="img-fluid" alt="MSSQL connection"></p>
</div>
<div id="tabset-2-2" class="tab-pane" aria-labelledby="tabset-2-2-tab">
<p>To test PostgreSQL I used <a href="https://hub.docker.com/layers/chriseaton/adventureworks/postgres/images/sha256-3d396f7e340138edf27f0ec6cd6b90e50da314a73d4cc7d98d7bf576ecac4faf">this</a> docker image by Chris Eaton with AdventureWorks database prepopulated. <img src="https://kpatucha.github.io/posts/JupySQL/postgres_ext_connect.png" class="img-fluid" alt="PostgreSQL connection"></p>
</div>
<div id="tabset-2-3" class="tab-pane" aria-labelledby="tabset-2-3-tab">
<p>To test Oracle I used <a href="https://hub.docker.com/layers/gvenzl/oracle-free/latest/images/sha256-d3760c92e53ce623e3f66e365209044a611ad7053230cfbd46f6c2958ee948a8">this</a> docker image by Gerald Venzl. <img src="https://kpatucha.github.io/posts/JupySQL/oracle_ext_connect.png" class="img-fluid" alt="Oracle connection"></p>
</div>
</div>
</div>
</section>
<section id="sqlalchemy-engine" class="level2">
<h2 class="anchored" data-anchor-id="sqlalchemy-engine">SQLAlchemy engine</h2>
<p>Create <a href="https://docs.sqlalchemy.org/en/20/core/connections.html#module-sqlalchemy.engine">SQLAlchemy engine</a></p>
<div class="tabset-margin-container"></div><div class="panel-tabset" data-group="db_type">
<ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" id="tabset-3-1-tab" data-bs-toggle="tab" data-bs-target="#tabset-3-1" aria-controls="tabset-3-1" aria-selected="true" href="">SQL Server</a></li><li class="nav-item"><a class="nav-link" id="tabset-3-2-tab" data-bs-toggle="tab" data-bs-target="#tabset-3-2" aria-controls="tabset-3-2" aria-selected="false" href="">PostgreSQL</a></li><li class="nav-item"><a class="nav-link" id="tabset-3-3-tab" data-bs-toggle="tab" data-bs-target="#tabset-3-3" aria-controls="tabset-3-3" aria-selected="false" href="">Oracle and others</a></li></ul>
<div class="tab-content" data-group="db_type">
<div id="tabset-3-1" class="tab-pane active" aria-labelledby="tabset-3-1-tab">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> getpass</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sqlalchemy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sa</span>
<span id="cb6-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pyodbc</span>
<span id="cb6-4"></span>
<span id="cb6-5">driver <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [driver <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> driver <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pyodbc.drivers() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ODBC"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> driver][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># take available ODBC driver</span></span>
<span id="cb6-6"></span>
<span id="cb6-7">connection_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.engine.URL.create(</span>
<span id="cb6-8">    drivername<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mssql+pyodbc"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># dialect+driver</span></span>
<span id="cb6-9">    username<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sa"</span>,</span>
<span id="cb6-10">    password<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>getpass.getpass(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># you can write password here in plain text or pass environment variable</span></span>
<span id="cb6-11">    host<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span>,</span>
<span id="cb6-12">    port<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1433"</span>,</span>
<span id="cb6-13">    database<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"AdventureWorks"</span>,</span>
<span id="cb6-14">    query<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{ <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># different key: value pairs for each type of database</span></span>
<span id="cb6-15">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"driver"</span>: driver,</span>
<span id="cb6-16">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Encrypted"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"yes"</span>,</span>
<span id="cb6-17">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TrustServerCertificate"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"yes"</span>,</span>
<span id="cb6-18">    },</span>
<span id="cb6-19">)</span>
<span id="cb6-20"></span>
<span id="cb6-21">engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.create_engine(connection_url)</span></code></pre></div></div>
</div>
<div id="tabset-3-2" class="tab-pane" aria-labelledby="tabset-3-2-tab">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> getpass</span>
<span id="cb7-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sqlalchemy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sa</span>
<span id="cb7-3"></span>
<span id="cb7-4">connection_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.engine.URL.create(</span>
<span id="cb7-5">    drivername<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"postgresql+psycopg"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># dialect+driver</span></span>
<span id="cb7-6">    username<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"postgres"</span>,</span>
<span id="cb7-7">    password<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>getpass.getpass(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># you can write password here in plain text or pass environment variable</span></span>
<span id="cb7-8">    host<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span>,</span>
<span id="cb7-9">    port<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5432"</span>,</span>
<span id="cb7-10">    database<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"postgres"</span>,</span>
<span id="cb7-11">)</span>
<span id="cb7-12"></span>
<span id="cb7-13">engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.create_engine(connection_url)</span></code></pre></div></div>
</div>
<div id="tabset-3-3" class="tab-pane" aria-labelledby="tabset-3-3-tab">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> getpass</span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sqlalchemy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sa</span>
<span id="cb8-3"></span>
<span id="cb8-4">connection_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.engine.URL.create(</span>
<span id="cb8-5">    drivername<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"oracle+oracledb"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># dialect+driver</span></span>
<span id="cb8-6">    username<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"my_user"</span>,</span>
<span id="cb8-7">    password<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>getpass.getpass(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># you can write password here in plain text or pass environment variable</span></span>
<span id="cb8-8">    host<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span>,</span>
<span id="cb8-9">    port<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1521"</span>,</span>
<span id="cb8-10">    query<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{ <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># different key: value pairs for each type of database</span></span>
<span id="cb8-11">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"service_name"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"FREEPDB1"</span></span>
<span id="cb8-12">    }</span>
<span id="cb8-13">)</span>
<span id="cb8-14"></span>
<span id="cb8-15">engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.create_engine(connection_url)</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="jupysql" class="level2">
<h2 class="anchored" data-anchor-id="jupysql">JupySQL</h2>
<p>Load <a href="https://jupysql.readthedocs.io/en/latest/quick-start.html">JupySQL</a> magics and pass <code>engine</code> to establish connection (best use <code>--alias</code> here for future reference)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>load_ext sql</span>
<span id="cb9-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>sql engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>alias my_db</span></code></pre></div></div>
</section>
<section id="sql-cell" class="level2">
<h2 class="anchored" data-anchor-id="sql-cell">SQL cell</h2>
<p>Change language of the cell to SQL either by:</p>
<ul>
<li>clicking in right bottom corner of the cell <img src="https://kpatucha.github.io/posts/JupySQL/select_language.png" class="img-fluid" alt="Select cell language"></li>
<li>using command palette (by default <code>Ctrl+Shift+P</code>) and choosing <code>Notebook: Change Cell Language</code></li>
<li>using shortcut <code>Ctrl+K, M</code> (by default)</li>
</ul>
<p><br>
<img src="https://kpatucha.github.io/posts/JupySQL/change_language.png" class="img-fluid" alt="Change language"></p>
<p>Make sure that the cell is connected to the database by looking at the little text at the top left of the cell (you might need to click it select the connection and database)</p>
<div class="tabset-margin-container"></div><div class="panel-tabset" data-group="db_type">
<ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" id="tabset-4-1-tab" data-bs-toggle="tab" data-bs-target="#tabset-4-1" aria-controls="tabset-4-1" aria-selected="true" href="">SQL Server</a></li><li class="nav-item"><a class="nav-link" id="tabset-4-2-tab" data-bs-toggle="tab" data-bs-target="#tabset-4-2" aria-controls="tabset-4-2" aria-selected="false" href="">PostgreSQL</a></li><li class="nav-item"><a class="nav-link" id="tabset-4-3-tab" data-bs-toggle="tab" data-bs-target="#tabset-4-3" aria-controls="tabset-4-3" aria-selected="false" href="">Oracle and others</a></li></ul>
<div class="tab-content" data-group="db_type">
<div id="tabset-4-1" class="tab-pane active" aria-labelledby="tabset-4-1-tab">
<p><br>
<img src="https://kpatucha.github.io/posts/JupySQL/mssql_cell.png" class="img-fluid" alt="MSSQL cell"></p>
</div>
<div id="tabset-4-2" class="tab-pane" aria-labelledby="tabset-4-2-tab">
<p><br>
<img src="https://kpatucha.github.io/posts/JupySQL/postgres_cell.png" class="img-fluid" alt="PostgreSQL cell"></p>
</div>
<div id="tabset-4-3" class="tab-pane" aria-labelledby="tabset-4-3-tab">
<p><br>
<img src="https://kpatucha.github.io/posts/JupySQL/oracle_cell.png" class="img-fluid" alt="Oracle cell"></p>
</div>
</div>
</div>
</section>
</section>
<section id="write-sql-in-the-cell" class="level1">
<h1>Write SQL in the cell</h1>
<p>Put <code>%%sql</code> magic at the top of the cell. You can now write SQL queries in the SQL cell and enjoy IntelliSense (context aware autocomplete) for SQL syntax and database objects as well as SQL formatting<sup>3</sup>.</p>
<p>I must admit the setup is kind of fragile. In case IntelliSense for database objects doesn’t work try one or all of these:</p>
<ul>
<li>using command palette (<code>Ctrl+Shift+P</code>) select <code>MS SQL: Refresh IntelliSense Cache</code> (or equivalent in other extension)</li>
<li>delete cell and create new one (change it’s language to SQL and connect it to database)</li>
<li>restart VS Code</li>
<li>(this one is weird) type your first SQL queries slowly, once it gets going you can type faster (maybe it has something to do with the fact that SQL IntelliSense in VS Code is kinda slow?)</li>
</ul>
<p><br>
<img src="https://kpatucha.github.io/posts/JupySQL/intellisense.png" class="img-fluid" alt="IntelliSense"></p>
</section>
<section id="work-with-pandas" class="level1">
<h1>Work with pandas</h1>
<p>In order to pass the result of the query to Pandas DataFrame there is a two step process</p>
<ol type="1">
<li><p>Assign result to a variable e.g.&nbsp;<code>sql_result</code> modyfying the <code>%%sql</code> magic</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>sql sql_result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;&lt;</span></span>
<span id="cb10-2">SELECT</span>
<span id="cb10-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb10-4">FROM Production.Product</span></code></pre></div></div></li>
<li><p>In next Python cell extract it to DataFrame</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">df_result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sql_result.DataFrame()</span></code></pre></div></div></li>
</ol>
<p>Alternatively, you can setup Pandas output globally (this allows to skip second step):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>config SqlMagic.autopanda <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span></code></pre></div></div>
<p>To save an existing DataFrame <code>df</code> to database you can use flag <code>--persist</code> or <code>--persist-replace</code> (table will have the same name as the DataFrame variable, <code>schema</code> is simply schema in the database)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>sql <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>persist schema.df</span>
<span id="cb13-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>sql <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>persist<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>replace schema.df </span></code></pre></div></div>
</section>
<section id="close-connection" class="level1">
<h1>Close connection</h1>
<p>To close connection use <code>--close</code> flag with connection alias</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>sql <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>close my_db</span></code></pre></div></div>
</section>
<section id="other-features" class="level1">
<h1>Other features</h1>
<p>There are a lot of other features in JupySQL like</p>
<ul>
<li>parametric queries using Jinja</li>
<li>working with multiple connections</li>
<li>query <code>.csv</code> and Excel files</li>
<li>plotting results of the queries</li>
</ul>
<p>and much more. Everything is cleanly explained in the <a href="https://jupysql.readthedocs.io/en/latest/quick-start.html">JupySQL documentation</a></p>


</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p>Recently <a href="https://learn.microsoft.com/en-us/sql/tools/visual-studio-code-extensions/mssql/mssql-sql-notebooks?view=sql-server-ver17">SQL notebooks</a> were added to the SQL Server (mssql) extension. They are for SQL only - you cannot work with Python AND SQL in the same notebook. Be careful not to change kernel to MSSQL - it overrides notebook metadata. When you try to go back to Python kernel ALL code cells will have language changed to SQL without easy option to go back - you need to open the notebook with text editor and delete <code>"metadata": {"vscode": {"languageId": "sql"}}</code> from each cell.↩︎</p></li>
<li id="fn2"><p>Although there is official <a href="https://marketplace.visualstudio.com/items?itemName=Oracle.sql-developer">Oracle extension</a> it doesn’t integrate with Jupyter notebooks nicely since it introduces new language PL/SQL which is not available for Jupyter notebook cells.↩︎</p></li>
<li id="fn3"><p>Depending on your formatting options it might not like <code>%%sql</code> magic as it is not part of standard SQL syntax - you can simply put it at the top of the cell just before execution.↩︎</p></li>
</ol>
</section><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">BibTeX citation:</div><pre class="sourceCode code-with-copy quarto-appendix-bibtex"><code class="sourceCode bibtex">@online{patucha2026,
  author = {Patucha, Konrad},
  title = {SQL in {Jupyter} {Notebook} {(JupySQL} + {VS} {Code} +
    {Jupyter} {Notebook)}},
  date = {2026-06-08},
  url = {https://kpatucha.github.io/posts/JupySQL/},
  langid = {en}
}
</code></pre><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-patucha2026" class="csl-entry quarto-appendix-citeas">
<div class="">K.
Patucha, <em>SQL in Jupyter Notebook (JupySQL + VS Code + Jupyter
Notebook) </em>, <a href="https://kpatucha.github.io/posts/JupySQL/">https://kpatucha.github.io/posts/JupySQL/</a>.</div>
</div></div></section></div> ]]></description>
  <category>Data Science</category>
  <guid>https://kpatucha.github.io/posts/JupySQL/</guid>
  <pubDate>Sun, 07 Jun 2026 22:00:00 GMT</pubDate>
  <media:content url="https://kpatucha.github.io/posts/JupySQL/intellisense.png" medium="image" type="image/png" height="68" width="144"/>
</item>
<item>
  <title>Dyck paths and Raney’s (cycle) lemma</title>
  <dc:creator>Konrad Patucha</dc:creator>
  <link>https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/</link>
  <description><![CDATA[ 





<section id="motivation" class="level1 page-columns page-full">
<h1>Motivation</h1>
<p>In this post I would like to show two methods to count number of <a href="https://mathworld.wolfram.com/DyckPath.html">Dyck paths</a> - special family of paths on square lattice. There are three main reasons why I think this is interesting problem:</p>
<ol type="1">
<li>It belongs to a family of very common counting problems (here is a <a href="https://youtu.be/fczN0BCx0xs?si=kheI7sN49gTZDzgr">YouTube video by Numberphile</a> about these problems)</li>
<li>The first method I will be presenting uses neat graphical trick which makes the problem very easy</li>
<li>The second method is more elaborate but highlights connection to cycle permutations which is useful in high-order petrubation theory in quantum mechanics (method I will be describing in future posts)</li>
</ol>
<p>Both methods were briefly described in this <a href="https://math.stackexchange.com/a/3237624">Stackexchange answer</a>. I’ve learned about Raney’s lemma from Qiaochu Yuan blog<span class="citation" data-cites="qiaochu2010">&nbsp;[1]</span> (although not named Raney’s lemma) and Tyler Neylon blog<span class="citation" data-cites="neylon2015">&nbsp;[2]</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-qiaochu2010" class="csl-entry">
<div class="csl-left-margin">[1] </div><div class="csl-right-inline">Y. Qiaochu, <a href="https://qchu.wordpress.com/2010/10/08/update-and-the-combinatorics-of-quintic-equations/">Update, and the combinatorics of quintic equations</a>, Annoying Precision (2010).</div>
</div><div id="ref-neylon2015" class="csl-entry">
<div class="csl-left-margin">[2] </div><div class="csl-right-inline">T. Neylon, <a href="http://gaarlicbread.com/tmp/raneys_lemmas.html">Notes on <span>Raney</span>’s <span>Lemmas</span></a>, GaarlicBread (2015).</div>
</div></div></section>
<section id="dyck-path" class="level1">
<h1>Dyck path</h1>
<div class="callout callout-style-simple callout-note no-icon">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>Dyck path</strong> is a path on a square lattice, that goes from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to point <img src="https://latex.codecogs.com/png.latex?(n,n)"> using only UP and RIGHT steps, and is always above or at most touches line <img src="https://latex.codecogs.com/png.latex?y=x"> (it cannot cross this line).</p>
</div>
</div>
</div>
<p>Maybe it is not common convention but let’s call Dyck path from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> <strong>Dyck path of order <img src="https://latex.codecogs.com/png.latex?n"></strong></p>
<div id="fc422064" class="cell" data-execution_count="1">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.axes <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Axes</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> itertools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> accumulate</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.special <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> comb</span>
<span id="cb1-6"></span>
<span id="cb1-7">plt.rcParams[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text.usetex"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb1-8"></span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> seq_to_path(</span>
<span id="cb1-11">    seq: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>], starting_point: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-12">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>]:</span>
<span id="cb1-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Map list of steps to a path on a square lattice</span></span>
<span id="cb1-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    - 1 == UP</span></span>
<span id="cb1-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    - 0 == RIGHT</span></span>
<span id="cb1-16"></span>
<span id="cb1-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb1-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb1-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    seq : list[int]</span></span>
<span id="cb1-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Sequence of steps</span></span>
<span id="cb1-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    starting_point : tuple[int, int], optional</span></span>
<span id="cb1-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Point at which to start a path, by default (0, 0)</span></span>
<span id="cb1-23"></span>
<span id="cb1-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb1-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -------</span></span>
<span id="cb1-26"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    tuple[list, list]</span></span>
<span id="cb1-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        List of x and list of y coordinates of points on a path</span></span>
<span id="cb1-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb1-29">    steps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(seq)</span>
<span id="cb1-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Concatenate [0] at the start to represent the initial starting point shift</span></span>
<span id="cb1-31">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> starting_point[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.concatenate(([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], np.cumsum(steps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)))</span>
<span id="cb1-32">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> starting_point[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.concatenate(([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], np.cumsum(steps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)))</span>
<span id="cb1-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x, y</span>
<span id="cb1-34"></span>
<span id="cb1-35"></span>
<span id="cb1-36">ax_good: Axes</span>
<span id="cb1-37">ax_bad: Axes</span>
<span id="cb1-38">fig, (ax_good, ax_bad) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb1-39"></span>
<span id="cb1-40">ax_good.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Dyck path"</span>)</span>
<span id="cb1-41">dyck_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> seq_to_path([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb1-42"></span>
<span id="cb1-43">ax_good.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb1-44">ax_good.plot(dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb1-45">ax_good.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-46">ax_good.grid()</span>
<span id="cb1-47">ax_good.set_yticks([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb1-48">ax_good.set_xticks([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb1-49"></span>
<span id="cb1-50">ax_bad.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Non-Dyck path"</span>)</span>
<span id="cb1-51">non_dyck_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> seq_to_path([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb1-52">ax_bad.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb1-53">ax_bad.plot(non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb1-54">ax_bad.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-55">ax_bad.grid()</span>
<span id="cb1-56">ax_bad.set_yticks([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb1-57">ax_bad.set_xticks([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb1-58"></span>
<span id="cb1-59">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-2-output-1.png" width="556" height="296" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Sometimes you can find different but equivalent versions of the definition e.g.:</p>
<ul>
<li>path is always <em>below</em> <img src="https://latex.codecogs.com/png.latex?y=x"></li>
<li>path is from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(2n,0)">, using only diagonal moves and never dips below line <img src="https://latex.codecogs.com/png.latex?y=0"> (kind of like ASCII mountain range built using symbols <code>\</code> and <code>/</code>)</li>
<li>path from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> using UP and RIGHT steps, where number of RIGHT steps at any point is less than or equal to number of UP steps</li>
</ul>
<p>General UP/RIGHT path from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> consists of <img src="https://latex.codecogs.com/png.latex?n"> UP steps and <img src="https://latex.codecogs.com/png.latex?n"> RIGHT steps - in total <img src="https://latex.codecogs.com/png.latex?2n"> steps. To count how many unique paths (not only Dyck paths) there are in total we need to determine in how many ways we can place <img src="https://latex.codecogs.com/png.latex?n"> UP steps in <img src="https://latex.codecogs.com/png.latex?2n"> places (the rest will be taken by RIGHT steps). This is exactly <a href="https://www.probabilitycourse.com/chapter2/2_1_3_unordered_without_replacement.php">unordered sampling without replacement</a>, so we have: <span id="eq-NAll"><img src="https://latex.codecogs.com/png.latex?%0AN_%5Ctext%7Ball%20paths%7D%20=%20%7B2n%20%5Cchoose%20n%7D%0A%5Ctag%7B1%7D"></span></p>
</section>
<section id="counting-dyck-paths---graphical-method" class="level1">
<h1>Counting Dyck paths - graphical method</h1>
<p>The problem is the following:</p>
<div class="callout callout-style-simple callout-note no-icon">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-body-container">
<p>How many Dyck paths from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> are there?</p>
</div>
</div>
</div>
<p>Imagine a <em>non-Dyck path</em> - at some point it crosses the <img src="https://latex.codecogs.com/png.latex?y=x"> line. Let’s call first step that makes the path a non-Dyck path <em>the bad step</em> - it causes the line to cross the <img src="https://latex.codecogs.com/png.latex?y=x"> line. Now reflect the part of the path from start up to the bad step with respect to line <img src="https://latex.codecogs.com/png.latex?y=x-1">.</p>
<div id="98a2d82d" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-2">ax.axes.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-3">reflected_part <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> seq_to_path([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], starting_point<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb2-4">ax.plot(non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb2-5">ax.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-6">ax.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-7">ax.plot(reflected_part[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], reflected_part[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reflected part"</span>)</span>
<span id="cb2-8"></span>
<span id="cb2-9">ax.text(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bad step"</span>, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb2-10">ax.text(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.7</span>, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"y=x-1"</span>, rotation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">45</span>)</span>
<span id="cb2-11">ax.legend()</span>
<span id="cb2-12">ax.grid()</span>
<span id="cb2-13">ax.set_yticks([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb2-14">ax.set_xticks([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-3-output-1.png" width="341" height="410" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>When we connect reflected part and the rest of the path we get a path from <img src="https://latex.codecogs.com/png.latex?(1,-1)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)">. In fact, each non-Dyck path will be mapped to different path from <img src="https://latex.codecogs.com/png.latex?(1,-1)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> and vice versa. To count paths from <img src="https://latex.codecogs.com/png.latex?(1,-1)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> (so non-Dyck paths equivalently) we can use same argument as counting <em>all paths</em>. This means that we have <img src="https://latex.codecogs.com/png.latex?2n"> steps in total of which <img src="https://latex.codecogs.com/png.latex?n-1"> are RIGHT steps:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AN_%5Ctext%7Bnon-Dyck%20paths%7D%20=%20%7B2n%20%5Cchoose%20n-1%7D%0A"></p>
<p>Together with Eq.&nbsp;1 this gives us total number of Dyck paths of order <img src="https://latex.codecogs.com/png.latex?n"> as: <span id="eq-NDyckPathsGraph"><img src="https://latex.codecogs.com/png.latex?%0AN_%5Ctext%7BDyck%20paths%7D%20=%20%7B2n%20%5Cchoose%20n%7D%20-%20%7B2n%20%5Cchoose%20n-1%7D%20=%20%5Cfrac%7B1%7D%7Bn+1%7D%20%7B2n%20%5Cchoose%20n%7D%0A%5Ctag%7B2%7D"></span></p>
<p>As promised, we got result that is famous in counting problems and is called <a href="https://en.wikipedia.org/wiki/Catalan_number">Catalan number</a> (in the Wikipedia article you will also find this proof in section <a href="https://en.wikipedia.org/wiki/Catalan_number#Second_proof">Second proof</a>)</p>
</section>
<section id="raneys-cycle-lemma" class="level1 page-columns page-full">
<h1>Raney’s (cycle) lemma</h1>
<p>To get to the second method let’s first discuss Raney’s lemma (there is more general cycle lemma<span class="citation" data-cites="dershowitz1990">&nbsp;[3]</span> but here we need this particular version):</p>
<div class="no-row-height column-margin column-container"><div id="ref-dershowitz1990" class="csl-entry">
<div class="csl-left-margin">[3] </div><div class="csl-right-inline">N. Dershowitz and S. Zaks, <a href="https://doi.org/10.1016/S0195-6698(13)80053-4">The <span>Cycle Lemma</span> and <span>Some Applications</span></a>, European Journal of Combinatorics <strong>11</strong>, 35 (1990).</div>
</div></div><div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Raney’s lemma
</div>
</div>
<div class="callout-body-container callout-body">
<p>We have sequence of <img src="https://latex.codecogs.com/png.latex?n"> integers which sums up to <img src="https://latex.codecogs.com/png.latex?1">:</p>
<p><span id="eq-Sum"><img src="https://latex.codecogs.com/png.latex?%0A%5Csum%5Climits_%7Bi=1%7D%5En%20x_i%20=%201%0A%5Ctag%7B3%7D"></span></p>
<p>There is <strong>only one</strong> cycle permutation of this sequence <img src="https://latex.codecogs.com/png.latex?x_i%5Crightarrow%20%5Ctilde%7Bx%7D_j=x_%7Bi+c%20%5Cbmod%20n%7D"> for which all cumulative sums are greater than <img src="https://latex.codecogs.com/png.latex?0">: <span id="eq-Cumsum"><img src="https://latex.codecogs.com/png.latex?%0A%5Csum%5Climits_%7Bj=1%7D%5Es%20%5Ctilde%7Bx%7D_j%20%3E%200%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s%20%5Cin%20%5B1,2,%5Cdots,n%5D%0A%5Ctag%7B4%7D"></span></p>
</div>
</div>
<p>To prove Raney’s lemma we can use visual proof.</p>
<p>First, let’s glue second copy of a sequence to our original sequence so we have a sequence of length <img src="https://latex.codecogs.com/png.latex?2n"> which satisfies: <img src="https://latex.codecogs.com/png.latex?%0Ax_%7Bi+n%7D%20=%20x_i%0A"></p>
<p>If we plot cumulative sums of this extended sequence we get something like this:</p>
<div id="9f4ddd1b" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">seq <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]</span>
<span id="cb3-2">cum_sums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(accumulate([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> seq))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we start from 0</span></span>
<span id="cb3-3">ext_cum_sums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(</span>
<span id="cb3-4">    accumulate([cum_sums[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> seq)</span>
<span id="cb3-5">)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we start from last element of first sequence</span></span>
<span id="cb3-6">min_cum_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(cum_sums)</span>
<span id="cb3-7">max_cum_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(ext_cum_sums)</span>
<span id="cb3-8"></span>
<span id="cb3-9">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-10">ax.grid()</span>
<span id="cb3-11">ax.plot(</span>
<span id="cb3-12">    [i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(cum_sums))],</span>
<span id="cb3-13">    cum_sums,</span>
<span id="cb3-14">    marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>,</span>
<span id="cb3-15">    ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb3-16">    label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sequence"</span>,</span>
<span id="cb3-17">    zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb3-18">)</span>
<span id="cb3-19">ax.plot(</span>
<span id="cb3-20">    [i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(cum_sums) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ext_cum_sums))],</span>
<span id="cb3-21">    ext_cum_sums,</span>
<span id="cb3-22">    marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>,</span>
<span id="cb3-23">    ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb3-24">    zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb3-25">    label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"copy of a sequence"</span>,</span>
<span id="cb3-26">)</span>
<span id="cb3-27">ax.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Cumulative sums for two copies of sequence </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>seq<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb3-28"></span>
<span id="cb3-29">ax.legend()</span>
<span id="cb3-30"></span>
<span id="cb3-31">ax.set_xticks([i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(seq) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)])</span>
<span id="cb3-32">ax.set_yticks(</span>
<span id="cb3-33">    np.linspace(</span>
<span id="cb3-34">        start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>min_cum_sum,</span>
<span id="cb3-35">        stop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_cum_sum,</span>
<span id="cb3-36">        endpoint<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb3-37">        num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_cum_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> min_cum_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb3-38">    )</span>
<span id="cb3-39">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-4-output-1.png" width="566" height="430" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Shifting start of the sequence in this representation is equivalent to cyclic permutation (order of elements is preserved and elements discarded from beginning of the original sequence are taken from the glued copy). If we shift the start to the global minimum of the cumulative sums, the resulting cyclic permutation of the sequence will satisfy condition Eq.&nbsp;4 for cumulative sums. In case the minimum is degenerate (like in presented example - there are two minima), we take the last minimum as our starting point.</p>
<div id="f8026450" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">min_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(cum_sums) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cum_sums[::<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].index(min_cum_sum)</span>
<span id="cb4-2">cum_sums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> min_cum_sum <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cum_sums]</span>
<span id="cb4-3">ext_cum_sums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> min_cum_sum <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ext_cum_sums]</span>
<span id="cb4-4">posit_cumsums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cum_sums[min_idx:] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> ext_cum_sums[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:min_idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-5"></span>
<span id="cb4-6">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-7">ax.grid()</span>
<span id="cb4-8">ax.plot(</span>
<span id="cb4-9">    [i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> min_idx <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(cum_sums))],</span>
<span id="cb4-10">    cum_sums,</span>
<span id="cb4-11">    marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>,</span>
<span id="cb4-12">    ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb4-13">    zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb4-14">)</span>
<span id="cb4-15">ax.plot(</span>
<span id="cb4-16">    [i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> min_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(cum_sums) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ext_cum_sums))],</span>
<span id="cb4-17">    ext_cum_sums,</span>
<span id="cb4-18">    marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>,</span>
<span id="cb4-19">    ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb4-20">    zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb4-21">)</span>
<span id="cb4-22">ax.plot(posit_cumsums, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>, zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"special cyclic permutation </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">ilde{x}</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-23"></span>
<span id="cb4-24">ax.hlines(y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, xmin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, xmax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(seq) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>)</span>
<span id="cb4-25">ax.legend()</span>
<span id="cb4-26">ax.set_xlim(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(seq) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)</span>
<span id="cb4-27">ax.set_xticks([i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(seq) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)])</span>
<span id="cb4-28">ax.set_yticks(</span>
<span id="cb4-29">    np.linspace(</span>
<span id="cb4-30">        start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(cum_sums),</span>
<span id="cb4-31">        stop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(ext_cum_sums),</span>
<span id="cb4-32">        endpoint<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb4-33">        num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(ext_cum_sums) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(cum_sums) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb4-34">    )</span>
<span id="cb4-35">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-5-output-1.png" width="556" height="410" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Therefore:</p>
<blockquote class="blockquote">
<p>The last minimum of the cumulative sums is starting point of the unique cyclic permutation that satisfies condition: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum%5Climits_%7Bj=1%7D%5Es%20%5Ctilde%7Bx%7D_j%20%3E%200%20%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s%5Cin%20%5B1,2,%5Ccdots,n%5D%0A"></p>
</blockquote>
<p><strong>This proves Raney’s lemma.</strong></p>
<p>Few comments why this shift is unique and why resulting cyclic permutation of sequence satisfies positivity of cumulative sums:</p>
<ul>
<li>The copies of the points of the glued sequence are greater by <img src="https://latex.codecogs.com/png.latex?1"> than original points (the whole original sequence sums up to <img src="https://latex.codecogs.com/png.latex?1"> from the definition Eq.&nbsp;3)</li>
<li><em>Last global minimum</em> is unique point</li>
<li>Non-last minimum would result in following minima at a value <img src="https://latex.codecogs.com/png.latex?y=0"> so corresponding to cumulative sums equal to <img src="https://latex.codecogs.com/png.latex?0"> - not strictly positive</li>
<li>Shifting start to any other point would result in minima below <img src="https://latex.codecogs.com/png.latex?y=0"> so negative cumulative sums</li>
</ul>
</section>
<section id="counting-dyck-paths---cyclic-permutations" class="level1">
<h1>Counting Dyck paths - cyclic permutations</h1>
<p>Equipped with Raney’s lemma we can move to second method of counting Dyck paths. But first we need to change representation of paths from sequence of UP and RIGHT steps to sequence of height of steps at each position:</p>
<div id="b0558e4b" class="cell" data-execution_count="5">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">dyck_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]]</span>
<span id="cb5-2">non_dyck_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]]</span>
<span id="cb5-3"></span>
<span id="cb5-4">fig, (ax_good, ax_bad) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-5"></span>
<span id="cb5-6">ax_good.plot(dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb5-7">ax_good.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-8"></span>
<span id="cb5-9">ax_good_top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax_good.twiny()</span>
<span id="cb5-10">ax_good_top.set_xlim(ax_good.get_xlim())</span>
<span id="cb5-11">ax_good_top.set_ylim(ax_good.get_ylim())</span>
<span id="cb5-12">ax_good.set_box_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-13">ax_good.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-14">ax_good_top.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-15">ax_good.grid()</span>
<span id="cb5-16">ax_good_top.set_xticks([i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)])</span>
<span id="cb5-17">ax_good_top.set_xticklabels([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"[2"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0]"</span>])</span>
<span id="cb5-18">ax_good_top.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Dyck path, step heights"</span>)</span>
<span id="cb5-19"></span>
<span id="cb5-20">ax_bad.plot(non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], non_dyck_path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb5-21">ax_bad.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-22"></span>
<span id="cb5-23">ax_bad_top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax_bad.twiny()</span>
<span id="cb5-24">ax_bad_top.set_xlim(ax_bad.get_xlim())</span>
<span id="cb5-25">ax_bad_top.set_ylim(ax_bad.get_ylim())</span>
<span id="cb5-26">ax_bad.set_box_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-27">ax_bad.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-28">ax_bad_top.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-29">ax_bad.grid()</span>
<span id="cb5-30">ax_bad_top.set_xticks([i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)])</span>
<span id="cb5-31">ax_bad_top.set_xticklabels([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"[1"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1]"</span>])</span>
<span id="cb5-32">ax_bad_top.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Non-Dyck path, step heights"</span>)</span>
<span id="cb5-33"></span>
<span id="cb5-34">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-6-output-1.png" width="556" height="319" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>In this representation general UP/RIGHT paths from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> can be defined as:</p>
<blockquote class="blockquote">
<p>Sequence of non-negative <img src="https://latex.codecogs.com/png.latex?n+1"> integers that sums to <img src="https://latex.codecogs.com/png.latex?n">: <span id="eq-SumPath"><img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5E%7Bn+1%7D%20h_i%20=%20n%0A%5Ctag%7B5%7D"></span></p>
</blockquote>
<p>and Dyck paths additionally satisfy constraint: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5Es%20h_i%20%5Cgeq%20s%20%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s%20%5Cin%20%5B1,2,%5Cdots,n%5D%0A"></p>
<p>We would like to group all UP/RIGHT paths from <img src="https://latex.codecogs.com/png.latex?(0,0)"> to <img src="https://latex.codecogs.com/png.latex?(n,n)"> into groups containing only cyclic permutations e.g.:</p>
<pre><code>[2, 0, 0, 1]
[1, 2, 0, 0]
[0, 1, 2, 0]
[0, 0, 1, 2]</code></pre>
<p>Since we have constraint Eq.&nbsp;5 and all <img src="https://latex.codecogs.com/png.latex?h_i%20%5Cgeq%200"> there is no possibility to make subcycles. In order to show this, we can map this problem to placing <img src="https://latex.codecogs.com/png.latex?n"> balls into <img src="https://latex.codecogs.com/png.latex?n+1"> boxes. To make subcycles we would have to split the sequence into <img src="https://latex.codecogs.com/png.latex?m"> equal parts, each containing <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Bn%7D%7Bm%7D"> balls. Finding size of subcycles is equivalent to finding greatest common denominator of <img src="https://latex.codecogs.com/png.latex?n"> and <img src="https://latex.codecogs.com/png.latex?n+1"> but this is: <img src="https://latex.codecogs.com/png.latex?%0A%5Cgcd(n,%20n+1)%20=%201%0A"></p>
<p>Therefore, there are no subcycles. Subcycles would lead to repeated elements within group of cyclic permutations. This means that:</p>
<blockquote class="blockquote">
<p>Each group of cyclic permutations has <img src="https://latex.codecogs.com/png.latex?n+1"> unique elements.</p>
</blockquote>
<p>Using this fact we can count total number of cyclic groups: <span id="eq-NcyclicGroups"><img src="https://latex.codecogs.com/png.latex?%0AN_%5Ctext%7Bcylic%20groups%7D%20=%20%5Cfrac%7BN_%5Ctext%7Ball%20paths%7D%7D%7Bn+1%7D%20=%20%5Cfrac%7B1%7D%7Bn+1%7D%20%7B2n%20%5Cchoose%20n%7D%0A%5Ctag%7B6%7D"></span></p>
<p>This is suspicious - the number of cyclic groups of UP/RIGHT paths is equal to number of Dyck paths Eq.&nbsp;2. We can follow this trail and potentially find more direct connection.</p>
<p>Let’s transform our sequence of step heights in the following way: <span id="eq-htob"><img src="https://latex.codecogs.com/png.latex?%0Ab_%7Bn+2-i%7D%20=%20-h_i%20+1%0A%5Ctag%7B7%7D"></span></p>
<p>The minus in front of <img src="https://latex.codecogs.com/png.latex?i"> index means that sequence <img src="https://latex.codecogs.com/png.latex?b"> is running in the reverse order compared to sequence <img src="https://latex.codecogs.com/png.latex?h">. However, sum from index <img src="https://latex.codecogs.com/png.latex?1"> to <img src="https://latex.codecogs.com/png.latex?n+1"> include all elements from both sequences Constraint Eq.&nbsp;5 for <img src="https://latex.codecogs.com/png.latex?b"> sequence takes the following form: <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bsplit%7D%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bn+1%7D%20b_j%20&amp;=%20%5Csum%5Climits_%7Bi=1%7D%5E%7Bn+1%7D(-h_i%20+%201)%20%5C%5C%0A&amp;=-%5Csum%5Climits_%7Bi=1%7D%5E%7Bn+1%7Dh_i%20+%20%5Csum%5Climits_%7Bi=1%7D%5E%7Bn+1%7D1%20%5C%5C%0A&amp;=-n%20+%20n%20+%201%20%5C%5C%0A&amp;=%201%0A%5Cend%7Bsplit%7D%0A"></p>
<p>For sequences of integer that sum up to <img src="https://latex.codecogs.com/png.latex?1"> we know from Raney’s lemma that there is only one cyclic permutation that satisfies: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bj=1%7D%5E%7Bs'%7D%20b_j%20%3E%200%20%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s'%5Cin%20%5B1,2,%5Cdots,n+1%5D%0A"></p>
<p>Let’s translate this statement back to original sequence of step heights <img src="https://latex.codecogs.com/png.latex?h"> reversing the formula Eq.&nbsp;7 (<img src="https://latex.codecogs.com/png.latex?-h_%7Bn+2-j%7D+1=b_j">): <span id="eq-hSumIneq"><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bsplit%7D%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bs'%7D(-h_%7Bn+2-j%7D%20+%201)%20&amp;%3E%200%20%5C%5C%0A-%5Csum%5Climits_%7Bj=1%7D%5E%7Bs'%7Dh_%7Bn+2-j%7D%20&amp;%3E%20-s'%20%5C%5C%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bs'%7Dh_%7Bn+2-j%7D%20&amp;%3C%20s'%0A%5Cend%7Bsplit%7D%0A%5Ctag%7B8%7D"></span></p>
<p>To transform this further we need to split the sum of all elements of <img src="https://latex.codecogs.com/png.latex?h"> in Eq.&nbsp;5 into two parts (again - if we sum all elements order in which summing index runs doesn’t matter): <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bsplit%7D%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bn+1%7D%20h_%7Bn+2-j%7D%20&amp;=%20n%5C%5C%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bs'%7D%20h_%7Bn+2-j%7D%20+%20%5Csum%5Climits_%7Bj=s'+1%7D%5E%7Bn+1%7D%20h_%7Bn+2-j%7D%20&amp;=n%20%5C%5C%0A%5Csum%5Climits_%7Bj=1%7D%5E%7Bs'%7D%20h_%7Bn+2-j%7D%20&amp;=%20n%20-%20%5Csum%5Climits_%7Bj=s'+1%7D%5E%7Bn+1%7D%20h_%7Bn+2-j%7D%0A%5Cend%7Bsplit%7D%0A"></p>
<p>Inserting this form into inequality Eq.&nbsp;8 gives us: <span id="eq-hSumIneq2"><img src="https://latex.codecogs.com/png.latex?%0A%5Csum%5Climits_%7Bj=s'+1%7D%5E%7Bn+1%7D%20h_%7Bn+2-j%7D%20%3E%20n-s'%0A%5Ctag%7B9%7D"></span></p>
<p>We can now rename indices in the following way: <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bcases%7D%0An+2-j%20&amp;%5Crightarrow%20i%5C%5C%0Aj%20=%20s'%20+%201%20&amp;%5Crightarrow%20i%20=%20n%20+%201%20-%20s'%20%5C%5C%0Aj%20=%20n%20+%201%20&amp;%5Crightarrow%20i%20=%201%20%5C%5C%0An%20+%201%20-s'%20&amp;%5Crightarrow%20s%0A%5Cend%7Bcases%7D%0A"></p>
<p>It is important to note here the range of possible values o <img src="https://latex.codecogs.com/png.latex?s"> - since <img src="https://latex.codecogs.com/png.latex?%5Cmin(s')%20=%201"> and <img src="https://latex.codecogs.com/png.latex?%5Cmax(s')=n+1">, this means that: <img src="https://latex.codecogs.com/png.latex?%0As%20%5Cin%20%5B0,1,%5Cdots,n%5D%0A"></p>
<p>Putting everything into inequality Eq.&nbsp;9 we get: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5Es%20h_i%20%3E%20s-1%20%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s%5Cin%5B0,1,%5Cdots,n%5D%0A"></p>
<p>For <img src="https://latex.codecogs.com/png.latex?s=0"> we sum empty sequence, so this is trivially satisfied (we have LHS:<img src="https://latex.codecogs.com/png.latex?%5Csum_%7Bi=1%7D%5E0%20h_i=0"> and RHS:<img src="https://latex.codecogs.com/png.latex?s-1=-1">, so <img src="https://latex.codecogs.com/png.latex?0%3E-1">). Since we are dealing with integers we can change <img src="https://latex.codecogs.com/png.latex?%3E"> to <img src="https://latex.codecogs.com/png.latex?%5Cgeq"> by getting rid of <img src="https://latex.codecogs.com/png.latex?-1">. This gives us: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5Es%20h_i%20%5Cgeq%20s%20%5Cquad%20%5Ctext%7Bfor%7D%20%5Cquad%20s%5Cin%5B1,%5Cdots,n%5D%0A"></p>
<p>From the above calculation we conclude that:</p>
<blockquote class="blockquote">
<p><strong>There can be only one</strong> cyclic permutation within each cyclic group that is Dyck path.</p>
</blockquote>
<p>Therefore, since we’ve established the number of cyclic groups Eq.&nbsp;6 we’ve also counted the number of Dyck paths <img src="https://latex.codecogs.com/png.latex?%0AN_%5Ctext%7BDyck%20paths%7D%20=%20N_%5Ctext%7Bcyclic%20groups%7D%20=%20%5Cfrac%7B1%7D%7Bn+1%7D%7B2n%20%5Cchoose%20n%7D%0A"></p>
<p>which is the same as in graphical method Eq.&nbsp;2 - <strong>Success!</strong></p>
<p>Although, this method was more elaborate than graphical method it highlights very important fact:</p>
<blockquote class="blockquote">
<p>Dyck paths correspond to unique generators of all cyclic groups for sequences defined by: <img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5E%7Bn+1%7Dh_i%20=%20n%20%5Cquad%5Ctext%7B,%7D%20%5Cquad%20h_i%20%5Cgeq%200%0A"></p>
</blockquote>
</section>
<section id="generating-dyck-paths" class="level1">
<h1>Generating Dyck paths</h1>
<p>Sometimes counting Dyck paths isn’t enough. We might want to generate all Dyck paths of given order. To achieve this we can use following recursive algorithm (inspired by algorithm on <a href="https://scipython.com/blog/dyck-paths-and-catalan-numbers/">scipython blog</a>):</p>
<ol type="1">
<li>Start from empty path</li>
<li>Run <em>all</em> following instructions for the path so far:
<ol type="i">
<li>If the path reached <img src="https://latex.codecogs.com/png.latex?(n,n)"> return it</li>
<li>If the number of UP steps is less than <img src="https://latex.codecogs.com/png.latex?n"> send to instruction 2. path so far with added UP step</li>
<li>If the number of RIGHT steps is less than number of UP steps send to instruction 2. path so far with added RIGHT step</li>
</ol></li>
</ol>
<p>In Python, this can be implemented using generators (they allow to iterate over some sequence similarilry to <code>range</code> or various generators from <code>itertools</code> module):</p>
<div id="14c740f0" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dyck_paths(n: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb7-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Generator producing Dyck paths of order `n`.</span></span>
<span id="cb7-3"></span>
<span id="cb7-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    - 1 == UP step</span></span>
<span id="cb7-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    - 0 == RIGHT step</span></span>
<span id="cb7-6"></span>
<span id="cb7-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb7-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    n : int</span></span>
<span id="cb7-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Order of Dyck paths</span></span>
<span id="cb7-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb7-12"></span>
<span id="cb7-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> make_path(path: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>, n_up: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, n_right: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb7-14">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># if path reached the end, yield it</span></span>
<span id="cb7-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(path) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n:</span>
<span id="cb7-16">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> path</span>
<span id="cb7-17"></span>
<span id="cb7-18">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add UP step if you can</span></span>
<span id="cb7-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n:</span>
<span id="cb7-20">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_path(path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_right)</span>
<span id="cb7-21"></span>
<span id="cb7-22">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add RIGHT step if you can</span></span>
<span id="cb7-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n_up:</span>
<span id="cb7-24">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_path(path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_up, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb7-25"></span>
<span id="cb7-26">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_path((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># start from single UP step</span></span></code></pre></div></div>
</div>
<p>Slightly modified version returns Dyck paths in step height representation:</p>
<div id="bd099e51" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dyck_path_heights(n: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb8-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Generator producing Dyck paths of order `n` in heights representation</span></span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Path has `n+1` heights.</span></span>
<span id="cb8-5"></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb8-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    n : int</span></span>
<span id="cb8-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Order of Dyck paths</span></span>
<span id="cb8-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb8-11"></span>
<span id="cb8-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> make_heights(path: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>, n_up: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, n_right: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb8-13">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># if path reached the end, yield it</span></span>
<span id="cb8-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n:</span>
<span id="cb8-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> path</span>
<span id="cb8-16"></span>
<span id="cb8-17">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add UP step if you can</span></span>
<span id="cb8-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n:</span>
<span id="cb8-19">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_heights(</span>
<span id="cb8-20">                path[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (path[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_right</span>
<span id="cb8-21">            )</span>
<span id="cb8-22"></span>
<span id="cb8-23">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add RIGHT step if you can</span></span>
<span id="cb8-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n_up:</span>
<span id="cb8-25">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_heights(path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_up, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb8-26"></span>
<span id="cb8-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> make_heights((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,), n_up<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<p>Let’s test it in action for order <img src="https://latex.codecogs.com/png.latex?n=4"></p>
<div id="64a17d87" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span></span>
<span id="cb9-2">catalan_number <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> comb(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n, n, exact<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, repetition<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> (n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb9-3"></span>
<span id="cb9-4">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(nrows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, ncols<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb9-5">ax: Axes</span>
<span id="cb9-6"></span>
<span id="cb9-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ax, seq, height_seq <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(axes.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), dyck_paths(n), dyck_path_heights(n)):</span>
<span id="cb9-8">    path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> seq_to_path(seq)</span>
<span id="cb9-9">    ax.plot(path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], path[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb9-10">    ax.plot([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,n], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,n], zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb9-11">    ax.set_aspect(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb9-12">    ax.set_xticks(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), height_seq)</span>
<span id="cb9-13">    ax.set_yticks([])</span>
<span id="cb9-14">    ax.xaxis.set_ticks_position(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span>
<span id="cb9-15"></span>
<span id="cb9-16">fig.delaxes(axes.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb9-17">fig.suptitle(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>catalan_number<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> Dyck paths of order </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb9-18">plt.show()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/index_files/figure-html/cell-9-output-1.png" width="540" height="427" class="figure-img"></p>
</figure>
</div>
</div>
</div>



</section>

<div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">BibTeX citation:</div><pre class="sourceCode code-with-copy quarto-appendix-bibtex"><code class="sourceCode bibtex">@online{patucha2026,
  author = {Patucha, Konrad},
  title = {Dyck Paths and {Raney’s} (Cycle) Lemma},
  date = {2026-05-03},
  url = {https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/},
  langid = {en}
}
</code></pre><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-patucha2026" class="csl-entry quarto-appendix-citeas">
<div class="">K.
Patucha, <em>Dyck Paths and Raney’s (Cycle) Lemma </em>, <a href="https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/">https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/</a>.</div>
</div></div></section></div> ]]></description>
  <category>Combinatorics</category>
  <guid>https://kpatucha.github.io/posts/Dyck-paths-Raneys-lemma/</guid>
  <pubDate>Sat, 02 May 2026 22:00:00 GMT</pubDate>
</item>
</channel>
</rss>
