<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikita Shpilevoy on Medium]]></title>
        <description><![CDATA[Stories by Nikita Shpilevoy on Medium]]></description>
        <link>https://medium.com/@nickshpilevoy?source=rss-279e59a6d2ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_oiwSkVblbN_5BmraXLXRQ.jpeg</url>
            <title>Stories by Nikita Shpilevoy on Medium</title>
            <link>https://medium.com/@nickshpilevoy?source=rss-279e59a6d2ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:05:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nickshpilevoy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python meta-programming code generation and manipulation at runtime]]></title>
            <link>https://medium.com/@nickshpilevoy/python-meta-programming-code-generation-and-manipulation-at-runtime-cc2433fa4842?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2433fa4842</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[bytecode]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 14:06:01 GMT</pubDate>
            <atom:updated>2024-10-04T14:06:01.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtZVfyi66QKwfY06" /><figcaption>AI-generated article preview image by DALL-E</figcaption></figure><p>Let’s push the boundaries even further with <strong>meta-programming techniques using code generation and manipulation at runtime</strong>, including <strong>bytecode manipulation</strong> using the dis module and exploring Python’s <strong>code object manipulation</strong>. These are some of the most advanced topics in Python because they deal with the very internals of how Python works at the bytecode and execution level.</p><h3>Goal: Modify Python Bytecode at Runtime</h3><p>We will explore:</p><ol><li><strong>Understanding and manipulating Python bytecode</strong> using the dis (disassembler) module.</li><li><strong>Creating and modifying Python code objects</strong> dynamically.</li><li><strong>Injecting custom behavior</strong> at the bytecode level.</li></ol><h3>Step 1: Introduction to Bytecode with the dis Module</h3><p>Python code is first compiled into <strong>bytecode</strong> (a low-level, platform-independent representation of the code) before it’s executed by the Python interpreter. We can inspect the bytecode using Python’s built-in dis module.</p><p>Here’s a simple example:</p><pre>import dis<br><br>def simple_function(a, b):<br>    return a + b<br><br># Disassemble the function to view its bytecode<br>dis.dis(simple_function)</pre><h4>Output:</h4><p>This will output the raw bytecode instructions for the simple_function. You’ll see operations like LOAD_FAST, BINARY_ADD, and RETURN_VALUE. These are the internal instructions the Python interpreter uses to execute your code.</p><h4>Explanation:</h4><ul><li><strong>LOAD_FAST</strong>: Loads a local variable onto the stack.</li><li><strong>BINARY_ADD</strong>: Adds the two top-most items on the stack.</li><li><strong>RETURN_VALUE</strong>: Pops the top item from the stack and returns it as the result of the function.</li></ul><h3>Step 2: Bytecode Manipulation — Modifying the Function’s Behavior</h3><p>You can actually <strong>change</strong> how a Python function behaves by manipulating its bytecode. Let’s modify the previous function so that it <strong>multiplies</strong> two numbers instead of adding them, without touching the original source code.</p><pre>import types<br><br>def add(a, b):<br>    return a + b<br><br># Disassemble to see original bytecode<br>dis.dis(add)<br><br># Let&#39;s change the bytecode manually<br>new_bytecode = list(add.__code__.co_code)<br><br># We will change the BINARY_ADD operation to BINARY_MULTIPLY<br># BINARY_ADD opcode is 23, BINARY_MULTIPLY opcode is 20<br>for i in range(len(new_bytecode)):<br>    if new_bytecode[i] == 23:  # BINARY_ADD<br>        new_bytecode[i] = 20  # Replace with BINARY_MULTIPLY<br><br># Now create a new code object<br>new_code = types.CodeType(<br>    add.__code__.co_argcount,  # Number of arguments<br>    add.__code__.co_posonlyargcount,<br>    add.__code__.co_kwonlyargcount,<br>    add.__code__.co_nlocals,<br>    add.__code__.co_stacksize,<br>    add.__code__.co_flags,<br>    bytes(new_bytecode),  # Modified bytecode<br>    add.__code__.co_consts,<br>    add.__code__.co_names,<br>    add.__code__.co_varnames,<br>    add.__code__.co_filename,<br>    add.__code__.co_name,<br>    add.__code__.co_firstlineno,<br>    add.__code__.co_lnotab,<br>    add.__code__.co_freevars,<br>    add.__code__.co_cellvars<br>)<br><br># Create a new function with the modified bytecode<br>new_function = types.FunctionType(new_code, globals())<br><br># Use the new function<br>print(new_function(2, 3))  # Output will be 6 (multiplication instead of addition)</pre><h4>Explanation:</h4><ol><li><strong>Disassembling the Function</strong>: We first disassemble the original function add to see its bytecode, which includes BINARY_ADD (opcode 23) for addition.</li><li><strong>Modifying Bytecode</strong>: We replace BINARY_ADD with BINARY_MULTIPLY (opcode 20) by directly altering the bytecode.</li><li><strong>Creating a New Code Object</strong>: We create a new CodeType object with the modified bytecode, then wrap it in a new function using types.FunctionType.</li><li><strong>Outcome</strong>: The resulting function now multiplies instead of adding, without changing the original source code.</li></ol><h3>Step 3: Dynamic Code Object Creation at Runtime</h3><p>Python’s <strong>code objects</strong> contain all the information needed to execute a function, such as the number of arguments, local variables, and the actual bytecode. Let’s create a function <strong>dynamically at runtime</strong> without writing it explicitly in the source code.</p><pre>import types<br><br># This code creates a function at runtime that behaves like this:<br># def dynamic_function(x, y):<br>#     return x * y<br># We&#39;ll directly construct the code object<br>bytecode = b&#39;|\x00|\x01\x14\x00S\x00&#39;  # This corresponds to: LOAD_FAST(0), LOAD_FAST(1), BINARY_MULTIPLY, RETURN_VALUE<br><br># Create a new code object manually<br>new_code = types.CodeType(<br>    2,               # Number of arguments (x, y)<br>    0,               # Number of positional-only arguments<br>    0,               # Number of keyword-only arguments<br>    2,               # Number of local variables<br>    2,               # Stack size<br>    67,              # Flags (standard function)<br>    bytecode,        # The raw bytecode instructions<br>    (),              # Constants used in the function (none here)<br>    (),              # Names referenced (none here)<br>    (&#39;x&#39;, &#39;y&#39;),      # Variable names<br>    &#39;&#39;,              # Filename (could be left empty)<br>    &#39;dynamic_function&#39;,  # Function name<br>    1,               # Line number<br>    b&#39;&#39;,             # lnotab (empty here)<br>    (),              # Free variables<br>    ()               # Cell variables<br>)<br><br># Create the actual function from the code object<br>dynamic_function = types.FunctionType(new_code, globals())<br><br># Test the dynamic function<br>print(dynamic_function(10, 5))  # Output: 50 (10 * 5)</pre><h4>Explanation:</h4><ol><li><strong>Bytecode Construction</strong>: We construct the bytecode manually to represent the sequence: LOAD_FAST, LOAD_FAST, BINARY_MULTIPLY, RETURN_VALUE. This is the core of the function’s behavior.</li><li><strong>Creating a Code Object</strong>: Using types.CodeType, we assemble all the parts of the function: the number of arguments, local variables, and the actual bytecode.</li><li><strong>Wrapping in a Function</strong>: We convert the CodeType object into a real function using types.FunctionType.</li><li><strong>Outcome</strong>: The dynamic_function behaves like a normal function, but it was generated entirely at runtime, and we never wrote the function explicitly in the source code.</li></ol><h3>Step 4: Injecting Dynamic Code into Existing Functions</h3><p>We can modify existing functions by injecting new behavior or additional operations dynamically.</p><p>Here’s an example where we inject a <strong>logging mechanism</strong> into a function dynamically by modifying its bytecode:</p><pre>import dis<br>import types<br><br>def target_function(a, b):<br>    return a * b<br><br>dis.dis(target_function)<br><br># Adding a logging statement<br># We want to inject this:<br># print(f&quot;Calculating {a} * {b}&quot;)<br>inject_bytecode = b&#39;|\x00|\x01\x14\x00S\x00&#39;  # LOAD_FAST(0), LOAD_FAST(1), BINARY_MULTIPLY, RETURN_VALUE<br>log_bytecode = b&#39;t\x00|\x00|\x01\x83\x02\x01\x00&#39;  # LOAD_GLOBAL (print), LOAD_FAST(0), LOAD_FAST(1), CALL_FUNCTION, POP_TOP<br><br># Combine the bytecodes (log before the function body)<br>combined_bytecode = log_bytecode + inject_bytecode<br><br># Creating a new code object with injected logging<br>new_code = types.CodeType(<br>    target_function.__code__.co_argcount,<br>    target_function.__code__.co_posonlyargcount,<br>    target_function.__code__.co_kwonlyargcount,<br>    target_function.__code__.co_nlocals,<br>    target_function.__code__.co_stacksize,<br>    target_function.__code__.co_flags,<br>    combined_bytecode,<br>    target_function.__code__.co_consts,<br>    target_function.__code__.co_names + (&#39;print&#39;,),<br>    target_function.__code__.co_varnames,<br>    target_function.__code__.co_filename,<br>    target_function.__code__.co_name,<br>    target_function.__code__.co_firstlineno,<br>    target_function.__code__.co_lnotab,<br>    target_function.__code__.co_freevars,<br>    target_function.__code__.co_cellvars<br>)<br><br># Wrap it into a new function<br>logged_function = types.FunctionType(new_code, globals())<br><br># Use the modified function<br>print(logged_function(5, 3))</pre><h4>Explanation:</h4><ol><li><strong>Original Function</strong>: We start with target_function which multiplies two numbers.</li><li><strong>Inject Logging Bytecode</strong>: We inject bytecode to log the values of a and b before the multiplication happens. This dynamically injects a print statement into the function.</li><li><strong>Combined Bytecode</strong>: The logging bytecode and the original function bytecode are combined, so logging happens first, followed by the original logic.</li><li><strong>Outcome</strong>: The new function prints a log message before returning the result.</li></ol><h3>Step 5: Real-World Use Cases for Bytecode and Code Manipulation</h3><ol><li><strong>Dynamic Optimization</strong>: You can inject optimizations or performance-critical paths into your code at runtime.</li><li><strong>Profiling and Debugging</strong>: By injecting logging, timing, or tracing bytecode into functions, you can dynamically profile and monitor performance without modifying the original source.</li><li><strong>Code Obfuscation and Encryption</strong>: Modify code objects at runtime to obfuscate logic or protect intellectual property.</li><li><strong>Domain-Specific Languages (DSLs)</strong>: Dynamically generate and inject code at runtime to handle specific business logic or computational models that are defined outside of the normal source code.</li><li><strong>Security Hardening</strong>: You can dynamically inject security checks (like input validation) into existing code.</li></ol><h3>Conclusion:</h3><p>Manipulating Python bytecode and creating custom code objects at runtime represents one of the most advanced techniques in Python meta-programming. It provides <strong>unparalleled control</strong> over how Python executes, allowing you to dynamically generate, optimize, and modify code on the fly. This can lead to incredibly powerful tools for optimization, monitoring, security, and dynamic behavior in Python programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2433fa4842" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s Just-in-Time (JIT) compilation using the Numba]]></title>
            <link>https://medium.com/@nickshpilevoy/python-numba-and-jit-compilation-b074dc7ccb53?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b074dc7ccb53</guid>
            <category><![CDATA[jit]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[just-in-time-compilation]]></category>
            <category><![CDATA[numba]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 18:24:03 GMT</pubDate>
            <atom:updated>2024-10-02T18:28:48.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_jCvPmtk2v6qnAuKx8hSwg.jpeg" /><figcaption>AI-generated article preview image by DALL-E</figcaption></figure><p>Let’s explore <strong>Python’s Just-in-Time (JIT) compilation</strong> using the <strong>Numba</strong> library. This allows you to dynamically compile Python functions to machine code at runtime for massive performance improvements in compute-heavy tasks. It’s a powerful way to optimize code execution in Python, especially for numerical and scientific computing, but it can also be generalized to any kind of intensive computation.</p><h3>Goal: Apply Just-in-Time Compilation for Performance Optimization</h3><p>We’ll explore how to:</p><ol><li>Leverage Numba’s <strong>JIT decorator</strong> to accelerate Python functions.</li><li>Use <strong>parallelism</strong> and <strong>vectorization</strong> features of Numba to optimize code that can run concurrently.</li><li>Compare performance between standard Python and JIT-compiled functions.</li></ol><h3>Step 1: Install Numba</h3><p>Before we start, you’ll need to install the Numba library:</p><pre>pip install numba</pre><h3>Step 2: Basic JIT Compilation Example</h3><p>We start by applying the <strong>@jit decorator</strong> to compile a function to machine code just-in-time, which accelerates its execution.</p><pre>from numba import jit<br>import time<br><br># A simple function to compute the sum of squares<br>@jit(nopython=True)  # nopython mode ensures full optimization<br>def sum_of_squares(n):<br>    total = 0<br>    for i in range(n):<br>        total += i * i<br>    return total<br><br># Measure the time without JIT<br>start_time = time.time()<br>print(sum_of_squares(10_000_000))  # JIT compiled<br>print(f&quot;Time with JIT: {time.time() - start_time} seconds&quot;)</pre><h4>Explanation:</h4><ul><li><strong>@jit(nopython=True)</strong>: This tells Numba to enforce the &quot;no-Python&quot; mode, where it compiles the function entirely into machine code without falling back to the Python interpreter. This mode gives the highest speedup.</li><li><strong>Result</strong>: The function will run orders of magnitude faster compared to regular Python, especially for large inputs like n=10,000,000.</li></ul><h3>Step 3: Parallel Execution with Numba</h3><p>Numba can automatically parallelize your code by using the <strong>@jit(parallel=True)</strong> option, which allows loops to be split and processed on multiple CPU cores.</p><p>Let’s use this feature to speed up a numerical computation that can benefit from parallelism.</p><pre>from numba import jit, prange<br><br>@jit(nopython=True, parallel=True)<br>def parallel_sum_of_squares(n):<br>    total = 0<br>    for i in prange(n):  # prange is a parallel version of range<br>        total += i * i<br>    return total<br><br># Measure the time with parallel execution<br>start_time = time.time()<br>print(parallel_sum_of_squares(10_000_000))  # Parallelized with JIT<br>print(f&quot;Time with parallel JIT: {time.time() - start_time} seconds&quot;)</pre><h4>Explanation:</h4><ul><li><strong>prange</strong>: This is a parallelized version of range that enables multi-threaded execution for the loop.</li><li><strong>@jit(parallel=True)</strong>: Tells Numba to try and parallelize the function. In the example above, the summation of squares can be computed independently across different CPU cores, leading to significant speedups.</li></ul><h3>Step 4: Vectorization and Automatic Optimization</h3><p>Numba can also automatically vectorize operations on arrays using <strong>NumPy</strong>. This leverages SIMD (Single Instruction, Multiple Data) instructions in modern CPUs, further improving performance.</p><p>Let’s take a matrix multiplication as an example, and let Numba optimize it.</p><pre>import numpy as np<br>from numba import jit<br><br># Define matrix multiplication<br>@jit(nopython=True, parallel=True)<br>def matrix_multiply(A, B):<br>    result = np.zeros((A.shape[0], B.shape[1]))<br>    for i in range(A.shape[0]):<br>        for j in range(B.shape[1]):<br>            for k in range(A.shape[1]):<br>                result[i, j] += A[i, k] * B[k, j]<br>    return result<br><br># Example usage:<br>N = 500<br>A = np.random.random((N, N))<br>B = np.random.random((N, N))<br><br># Measure the time with JIT optimization<br>start_time = time.time()<br>C = matrix_multiply(A, B)<br>print(f&quot;Time with JIT for matrix multiplication: {time.time() - start_time} seconds&quot;)</pre><h4>Explanation:</h4><ul><li><strong>Automatic Parallelism</strong>: Numba will automatically optimize the matrix multiplication to run in parallel across multiple cores.</li><li><strong>Vectorization</strong>: Numba takes advantage of CPU vector instructions, which handle arrays more efficiently.</li></ul><h3>Step 5: Benchmarking Performance with and without JIT</h3><p>Let’s now compare the performance of a regular Python function versus the JIT-compiled function. For simplicity, we’ll use a basic computational function.</p><pre>import time<br><br># Regular Python version (without JIT)<br>def regular_sum_of_squares(n):<br>    total = 0<br>    for i in range(n):<br>        total += i * i<br>    return total<br>n = 10_000_000<br><br># Measure performance of regular Python function<br>start_time = time.time()<br>print(regular_sum_of_squares(n))<br>print(f&quot;Regular Python time: {time.time() - start_time} seconds&quot;)<br><br># Measure performance of JIT-compiled function<br>start_time = time.time()<br>print(sum_of_squares(n))  # Using the previously defined JIT function<br>print(f&quot;JIT compiled time: {time.time() - start_time} seconds&quot;)</pre><h4>Explanation:</h4><ul><li><strong>Regular Python</strong>: This runs the unoptimized Python version.</li><li><strong>JIT-Compiled Version</strong>: This runs the JIT-compiled version of the same function.</li></ul><p>You should observe a <strong>significant performance improvement</strong> with the JIT-compiled version, especially as the input size (n) grows large.</p><h3>Step 6: Numba with GPU Acceleration</h3><p>Numba can also target <strong>GPU execution</strong> with minimal changes to your code. If you have a CUDA-capable GPU, you can use Numba’s cuda.jit to execute code on the GPU for massive performance improvements.</p><p>Here’s a basic example of summing an array on the GPU.</p><pre>import numpy as np<br>from numba import cuda<br><br># Define a CUDA kernel<br>@cuda.jit<br>def gpu_sum(array, result):<br>    idx = cuda.grid(1)  # Get the thread ID<br>    if idx &lt; array.size:<br>        cuda.atomic.add(result, 0, array[idx])<br><br># Example usage:<br>N = 10000000<br>array = np.ones(N, dtype=np.float32)<br>result = np.array([0.0], dtype=np.float32)<br><br># Configure the GPU grid (blocks and threads)<br>threads_per_block = 256<br>blocks_per_grid = (array.size + (threads_per_block - 1)) // threads_per_block<br><br># Launch the kernel on the GPU<br>gpu_sum[blocks_per_grid, threads_per_block](array, result)<br>print(f&quot;Result of GPU sum: {result[0]}&quot;)</pre><h4>Explanation:</h4><ul><li><strong>CUDA Kernel</strong>: The function gpu_sum is written to run on the GPU. It sums the values in the array using GPU threads.</li><li><strong>Atomic Operations</strong>: Since multiple threads operate in parallel, we use cuda.atomic.add to safely accumulate values into the result array.</li><li><strong>Parallel Execution on GPU</strong>: The computation is spread across many GPU cores, making it highly efficient for large datasets.</li></ul><h3>Key Concepts in JIT and GPU Acceleration:</h3><ol><li><strong>Just-in-Time Compilation (JIT)</strong>: JIT compiles Python functions into optimized machine code on the fly, leading to massive speedups, particularly for compute-heavy tasks.</li><li><strong>Parallel Execution</strong>: Numba can automatically parallelize code across multiple CPU cores with minimal changes to the code (using @jit(parallel=True)).</li><li><strong>GPU Acceleration</strong>: By using Numba’s CUDA support, you can leverage GPU hardware for even more performance improvements, especially for large datasets and operations that can be parallelized.</li><li><strong>Vectorization</strong>: Numba automatically optimizes for SIMD instructions, which improves performance for numerical operations on arrays or matrices.</li><li><strong>Ease of Use</strong>: Numba requires very minimal code modification. You just need to apply decorators like @jit or @cuda.jit, and the rest is handled automatically.</li></ol><h3>When to Use Numba and JIT Compilation:</h3><ul><li><strong>Numerical Computing</strong>: Ideal for algorithms involving loops, matrix manipulations, and numerical calculations.</li><li><strong>Data Science</strong>: For handling large datasets, especially with NumPy arrays.</li><li><strong>Machine Learning</strong>: Accelerate training or inference code for machine learning models.</li><li><strong>Scientific Simulations</strong>: Useful in physics simulations, financial modeling, or any other domain requiring fast calculations.</li></ul><h3>Conclusion:</h3><p>By using <strong>Numba’s JIT compiler</strong>, you can easily turn Python into a high-performance computing language without rewriting the code in C or C++. When you combine this with <strong>parallelism</strong> and <strong>GPU acceleration</strong>, you can handle even the most demanding computational tasks efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b074dc7ccb53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SQL Techniques and Complex Queries in PostgreSQL]]></title>
            <link>https://medium.com/@nickshpilevoy/postgresql-advanced-queries-optimization-and-practices-991917a3725c?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/991917a3725c</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 14:35:12 GMT</pubDate>
            <atom:updated>2024-10-02T18:24:34.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-0ao2uXcOBiKQwJ2y0zWlQ.jpeg" /><figcaption>AI-generated article preview image by DALL-E</figcaption></figure><p>PostgreSQL stands out as a open source RDBMS known for its adherence, to SQL standards and robust performance capabilities. While basic SQL operations, such as simple SELECT, INSERT, UPDATE, and DELETE queries, are sufficient for straightforward use cases, however in scenarios, such as those encountered in real world applications advanced SQL methods are often required. These methods enable users to manage datasets run queries efficiently and uphold optimal performance levels. The primary focus of this study is to delve into techniques, within the PostgreSQL environment.</p><p>We explore SQL techniques, like queries with WITH RECURSION and window functions for analytics purposes along with effective join methods and other optimization approaches. We also look into the benefits of open source add ons such as PostGIS, for managing data and pg_partman for streamlining partitioning tasks.</p><h3>Recursive Queries and Hierarchical Data</h3><h4>Common Table Expressions (CTEs)</h4><p>CTEs are handy, for simplifying queries into manageable segments and can even handle recursion well for hierarchical data, like organization charts or category trees.</p><p>Example:</p><pre>WITH RECURSIVE cte_name AS (<br>    -- Base case (anchor member)<br>    SELECT ...<br>    FROM ...<br>    WHERE ...<br><br>    UNION ALL<br><br>    -- Recursive case (recursive member)<br>    SELECT ...<br>    FROM cte_name<br>    JOIN ...<br>    ON ...<br>)<br>SELECT * FROM cte_name;</pre><p>For example, consider a table employee with the columns id, name, and manager_id representing an employee hierarchy. To retrieve the entire hierarchy for a given manager, one can use:</p><pre>WITH RECURSIVE employee_hierarchy AS (<br>    SELECT id, name, manager_id<br>    FROM employee<br>    WHERE manager_id IS NULL  -- Assuming the CEO has no manager<br><br>    UNION ALL<br><br>    SELECT e.id, e.name, e.manager_id<br>    FROM employee e<br>    JOIN employee_hierarchy eh ON e.manager_id = eh.id<br>)<br>SELECT * FROM employee_hierarchy;</pre><h3>Window Functions</h3><h4>Window Functions for Analytical Queries</h4><p>Window functions allow you to perform calculations across rows related to the current row within a defined window. PostgreSQL offers a rich set of window functions such as ROW_NUMBER(), RANK(), LEAD(), LAG(), and aggregate window functions like SUM(), AVG(), etc.</p><p>For example, you can rank employees by their salary within each department:</p><pre>SELECT id, name, department, salary,<br>       RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank<br>FROM employee;</pre><p>This query ranks employees within each department, partitioned by the department column, with salaries ordered in descending order.</p><h3>Query Optimization Strategies</h3><h4>Indexing</h4><p>Indexing is a fundamental optimization technique in PostgreSQL. B-tree indexes are commonly used for sorting and searching operations, while other index types like GIN (Generalized Inverted Index) and GiST (Generalized Search Tree) are better suited for full-text search and spatial queries.</p><p>Consider the following query:</p><pre>SELECT * FROM orders WHERE customer_id = 12345;</pre><p>Creating an index on customer_id can significantly speed up this query:</p><pre>CREATE INDEX idx_customer_id ON orders(customer_id);</pre><h4>Partitioning</h4><p>Partitioning is crucial for managing large tables by breaking them into smaller, more manageable pieces. PostgreSQL supports range, list, and hash partitioning. For example, a range partitioning of a time-series dataset can be implemented as:</p><pre>CREATE TABLE orders (<br>    id SERIAL PRIMARY KEY,<br>    order_date DATE,<br>    amount DECIMAL<br>) PARTITION BY RANGE (order_date);<br><br>CREATE TABLE orders_2023 PARTITION OF orders<br>FOR VALUES FROM (&#39;2023-01-01&#39;) TO (&#39;2023-12-31&#39;);</pre><h4>Query Planner and Execution</h4><p>PostgreSQL’s query planner evaluates multiple potential query execution plans and selects the most efficient one based on cost estimation. Cost is computed based on factors like I/O operations, CPU time, and memory usage. The total cost function can be expressed as:</p><figure><img alt="C_{\text{total}} = C_{\text{io}} + C_{\text{cpu}} + C_{\text{mem}}" src="https://cdn-images-1.medium.com/max/224/0*lgJot42QcPFJqDy9.png" /></figure><p>Where:</p><ul><li><strong>io</strong> is the cost related to disk I/O,</li><li><strong>cpu</strong> is the cost of CPU processing, and</li><li><strong>mem</strong> accounts for memory consumption.</li></ul><p>The query planner seeks to minimize <strong>total</strong>, often making use of available indexes, joins, and filters.</p><h3>Open-Source Extensions</h3><h3>PostGIS</h3><p>PostGIS adds support for geographic objects, allowing location queries to be run in SQL. For example, a spatial query to find all points within a given radius can be written as:</p><pre>SELECT name<br>FROM locations<br>WHERE ST_DWithin(<br>    geography(location), <br>    geography(ST_MakePoint(-71.064544, 42.28787)), <br>    10000<br>);</pre><p>This query finds all locations within 10 kilometers of a given point.</p><h4>pg_partman</h4><p>pg_partman is an open-source extension for PostgreSQL that simplifies the creation and management of partitioned tables. It automates partitioning strategies based on ranges or intervals, significantly improving the performance of time-series databases.</p><h3>References</h3><ol><li>PostgreSQL Documentation. (2024). <em>PostgreSQL 17 Documentation</em>. Available at: <a href="https://www.postgresql.org/docs/">https://www.postgresql.org/docs/</a></li><li>Ramakrishnan, R., &amp; Gehrke, J. (2003). <em>Database Management Systems</em> (3rd ed.). McGraw-Hill.</li><li>Obe, R. O., &amp; Hsu, L. S. (2011). <em>PostGIS in Action</em>. Manning Publications.</li><li>Stonebraker, M., &amp; Çetintemel, U. (2005). “One Size Fits All”: An Idea Whose Time Has Come and Gone. In <em>Proceedings of the 21st International Conference on Data Engineering</em> (pp. 2–11).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991917a3725c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms: An Overview of Time Complexities]]></title>
            <link>https://medium.com/@nickshpilevoy/sorting-algorithms-time-complexity-comparison-a4285365f02f?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4285365f02f</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[sort]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 13:36:38 GMT</pubDate>
            <atom:updated>2024-09-28T13:37:45.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fzfP5ji9MJDrxTu_0mZw.png" /></figure><h3>Efficient in Production</h3><h4><strong>Quicksort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log n) on average, O(n²) worst-case.</li><li><strong>Why it’s effective</strong>: Quicksort is highly efficient in practice because of its low overhead and good cache performance, which makes it faster than many other O(n log n) algorithms. It’s often the default choice in many programming languages and libraries.</li><li><strong>When to use</strong>: It’s typically used for general-purpose sorting, especially when memory usage and typical-case performance are more important than worst-case performance.</li><li><strong>Note</strong>: It is the default sorting algorithm in many programming languages, such as Python like Python (sorted() and list.sort()), JavaScript (Array.prototype.sort), Go (sort.Sort), etc.</li></ul><h4><strong>IntroSort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log n) worst-case.</li><li><strong>Why it’s effective</strong>: IntroSort begins with Quicksort but switches to Heapsort if the recursion depth exceeds a certain threshold (to avoid Quicksort’s O(n²) worst-case). It combines the fast average-case performance of Quicksort with the guaranteed O(n log n) worst-case behavior of Heapsort.</li><li><strong>When to use</strong>: Many C++ Standard Template Library (STL) implementations use IntroSort because it provides a balance between speed and worst-case performance. It’s particularly useful when you need a general-purpose, efficient sort but also want to guard against bad pivot choices in Quicksort.</li><li><strong>Note 1:</strong> C++ Standard Library (std::sort) implements a <strong>hybrid sorting algorithm</strong>, which begins with <strong>Introsort</strong> (Quicksort with a switch to Heapsort when the recursion depth exceeds a limit) and typically switches to <strong>Insertion Sort</strong> for small partitions. This combination optimizes for both speed and worst-case performance.</li><li><strong>Note 2:</strong> Rust uses <strong>Introsort </strong>for<strong> </strong>slice::sort, which starts with Quicksort and switches to Heapsort when necessary to avoid Quicksort’s worst-case behavior. It ensures O(n log n) worst-case performance.</li></ul><h4><strong>Mergesort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log n) in all cases.</li><li><strong>Why it’s effective</strong>: Mergesort guarantees a stable sort and consistent O(n log n) performance, making it reliable in scenarios where worst-case performance is crucial.</li><li><strong>When to use</strong>: It’s especially useful when you need a stable sorting algorithm or when sorting linked lists. It’s also preferred in external sorting (sorting data that doesn’t fit in memory).</li></ul><h4><strong>Heapsort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log n).</li><li><strong>Why it’s effective</strong>: Heapsort provides consistent performance with O(n log n) time complexity and works in place with O(1) extra memory.</li><li><strong>When to use</strong>: Suitable for memory-constrained environments where an in-place sort is necessary, though it’s generally slower than Quicksort due to poor cache locality.</li></ul><h4><strong>Timsort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log n) in worst-case, O(n) for nearly sorted data.</li><li><strong>Why it’s effective</strong>: Timsort is a hybrid sorting algorithm derived from Mergesort and Insertion sort. It’s optimized for real-world data patterns like partially sorted data. It is highly efficient in practice and is used in many standard libraries (Python, Java, etc.).</li><li><strong>When to use</strong>: Best for datasets that are likely to have ordered runs, as it exploits these runs for better performance.</li></ul><h4><strong>Radix Sort (and Counting Sort)</strong></h4><ul><li><strong>Time Complexity</strong>: O(nk) where k is the number of digits or bits per element.</li><li><strong>Why it’s effective</strong>: Radix Sort can sort integers or strings efficiently by processing digit by digit, making it faster than comparison-based sorts for certain types of data.</li><li><strong>When to use</strong>: Particularly effective for fixed-size, numeric data where the number of digits or bits (k) is small relative to the dataset size (n).</li></ul><h3>Not Recommended for Production</h3><h4><strong>Bubble Sort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n²).</li><li><strong>Why it’s ineffective</strong>: Bubble Sort is slow and inefficient for large datasets due to its quadratic time complexity, making it impractical for most production scenarios.</li><li><strong>When to avoid</strong>: For any non-trivial data sizes, as it will be outperformed by other algorithms.</li></ul><h4><strong>Selection Sort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n²).</li><li><strong>Why it’s ineffective</strong>: Selection Sort performs poorly on large datasets and offers no benefits over more efficient algorithms like Quicksort or Mergesort.</li><li><strong>When to avoid</strong>: Almost always, except for educational purposes or specific cases where the number of swaps must be minimized.</li></ul><h4><strong>Insertion Sort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n²) worst-case, O(n) best-case for nearly sorted data.</li><li><strong>Why it’s ineffective</strong>: While Insertion Sort performs well for small or nearly sorted datasets, it is impractical for large datasets due to its quadratic time complexity.</li><li><strong>When to avoid</strong>: For large, unsorted datasets. However, it’s effective when the data is already nearly sorted or the dataset is small (e.g., Timsort uses Insertion Sort for small subarrays).</li></ul><h4><strong>Shell Sort</strong></h4><ul><li><strong>Time Complexity</strong>: O(n log² n) on average, with worst-case variations depending on the gap sequence.</li><li><strong>Why it’s ineffective</strong>: Though it’s faster than Insertion Sort for large datasets, its complexity is not well-defined, and it’s often outperformed by more modern algorithms like Timsort or Quicksort.</li><li><strong>When to avoid</strong>: When more predictable performance is needed, or when more efficient alternatives are available.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4285365f02f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quadratic Time Complexity]]></title>
            <link>https://medium.com/@nickshpilevoy/quadratic-time-complexity-86f81e57e54e?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f81e57e54e</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 11:58:14 GMT</pubDate>
            <atom:updated>2024-09-28T12:46:04.721Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@nickshpilevoy/understanding-big-o-notation-basics-by-examples-c2ac8ba83d7e">In the previous chapter</a>, we explained Big O complexity and covered both linear and logarithmic complexities. If you’re just getting started, I recommend reading that article first.</p><h3><strong>Quadratic Time Complexity</strong></h3><p>Let’s break down this code:</p><pre>matrix = [<br>  [1,2,3,4,5]<br>  [2,3,4,5,6]<br>  [3,4,5,6,7]<br>  [4,5,6,7,8]<br>]<br><br>matrix_sum = 0<br>for i in range(len(matrix)):<br>  for j in range(len(matrix[i])):<br>    matrix_sum += matrix[i][j]<br><br>print(matrix_sum)</pre><p>In this code, we’re treating string comparison as the most time-consuming operation. So, how many times do we expect to run it in the worst-case scenario?</p><p>The correct answer is 20.</p><p>You can visualize the solution using a simple geometric approach — grab a piece of paper and draw a 4x5 grid, then count the number of cells. This mirrors how the code goes through the two-dimensional array.</p><pre>| 1 | 2 | 3 | 4 | 5 |<br>| 2 | 3 | 4 | 5 | 6 |<br>| 3 | 4 | 5 | 6 | 7 |<br>| 4 | 5 | 6 | 7 | 8 |</pre><p>A nested loop is the easiest example of quadratic complexity, also known as O(n²).</p><h3><strong>Cubic Time Complexity</strong></h3><p>Let’s break down this code:</p><pre>tensor3d = [<br>  [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]]<br>  [[2,3,4,5,6], [2,3,4,5,6], [2,3,4,5,6]]<br>  [[3,4,5,6,7], [3,4,5,6,7], [3,4,5,6,7]]<br>  [[4,5,6,7,8], [4,5,6,7,8], [4,5,6,7,8]]<br>]<br><br>tensor_sum = 0<br>for i in range(len(tensor3d)):<br>  for j in range(len(tensor3d[i])):<br>    for k in range(len(tensor3d[i][j])):<br>      tensor_sum += tensor3d[i][j][k]<br><br>print(tensor_sum)</pre><p>It’s similar to the previous example, but now we have 3 loops instead of 2.</p><p>So, the same question: how many times do we expect to run it in the worst case?</p><p>The correct answer is 60.</p><p>The time complexity of this code is O(n³), also known as cubic time complexity.</p><h3><strong>Quartic, Quintic, Sextic, etc.</strong></h3><p>I think you’ve got the idea by now, so we don’t need to go further into detail. Each additional nested loop typically increases the time complexity by another order of <strong><em>n</em></strong>. So, if you come across code with 6 nested loops, you can guess it likely has sextic time complexity.</p><p>However, this isn’t a hard rule, as certain algorithms can have optimizations or other factors that change the number of iterations significantly, either increasing or decreasing the overall complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVU70dqTwRc_rXh4TQZ_kw.png" /><figcaption>Comparison of quadratic, cubic and Quartic time complexity</figcaption></figure><h3>Real-Life Examples of O(n²)</h3><h4><strong>Direct Convolution</strong></h4><p>Direct convolution, in simple terms, is a method used to combine two signals or sequences to produce a third one. The result shows how one sequence “blends” with the other over time or space. The process can be described by the following formula:</p><p>y[n]=∑k=0N−1x[k]⋅h[n−k]y[n] = \sum_{k=0}^{N-1} x[k] \cdot h[n-k]y[n]=∑k=0N−1​x[k]⋅h[n−k]</p><p>Now, let’s transcribe the math formula into Python code:</p><pre>def direct_convolution(x, h):<br>    N = len(x)<br>    y = [0] * (2 * N - 1)  # Resultant sequence length<br>    for n in range(len(y)):<br>        for k in range(N):<br>            if 0 &lt;= n - k &lt; N:<br>                y[n] += x[k] * h[n - k]<br>    return y</pre><p>In this code, the first loop iterates 2<strong>n</strong> times, which gives us a time complexity of O(2<strong>n</strong>) or simply O(<strong>n</strong>).</p><p>The second loop iterates <strong><em>n</em></strong> times, contributing O(<strong>n</strong>) to the complexity.</p><p>We also have a condition that reduces the number of operations by half, but from a complexity perspective, we ignore constants like division by 2. So, we don’t need to factor that in.</p><p>Overall, this gives us a time complexity of O(n²).</p><p>However, this algorithm can be optimized using the Fast Fourier Transform (FFT), which reduces the complexity to O(n log n). But that’s a topic for another article.</p><h4>Bubble sort</h4><p>Bubble sort is terrible for production, but it’s the simplest sorting algorithm, so let’s take a look at it.</p><pre>def bubbleSort(array: list):<br>    n = len(array)<br>    swapped = True<br>    <br>    while swapped:<br>        swapped = False<br>        for i in range(1, n):<br>            if array[i - 1] &gt; array[i]:<br>                # Swap the elements<br>                array[i - 1], array[i] = array[i], array[i - 1]<br>                swapped = True<br>    return array</pre><p>(I took this code from Wikipedia and rewrote it in Python to make it easier to understand.)</p><p><strong>What do we see here?</strong></p><p>There’s a for loop—it&#39;s very straightforward and runs <em>n</em> times, so we can say it gives us O(n).</p><p>The while loop is a bit trickier. Since it’s conditional, we need to look closer at what’s happening. The code checks if any swaps were made during the inner loop. If a swap happened, the loop runs again, continuing until the array is fully sorted. In the worst-case scenario—when the array is reverse sorted—we’ll need to rerun the loop about <em>n/2</em> times to rearrange every pair of numbers. This means we can also consider the while loop as O(n). (We ignore the constant factor, like <em>n/2</em>, when talking about Big O notation.)</p><p>So, we have O(n) for the for loop and O(n) for the while loop, which together give us O(n²).</p><p>O(n²) is terrible for a sorting algorithm, and that’s why I mentioned that bubble sort isn’t used in production.</p><p>More efficient sorting algorithms usually have a time complexity of O(n log n), which we’ll dive into in the next article. Make sure to subscribe so you don’t miss it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f81e57e54e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Big O Notation Basics with Examples]]></title>
            <link>https://medium.com/@nickshpilevoy/understanding-big-o-notation-basics-by-examples-c2ac8ba83d7e?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2ac8ba83d7e</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[big-o]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 15:35:46 GMT</pubDate>
            <atom:updated>2024-09-28T12:44:01.772Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s break it down from a practical perspective.</p><p>Say we need to find a word in a Defining Dictionary. In our code, it is just an array of words, or strings. The simplest way to handle this task is by going through the array one word at a time, checking each one to see if it matches.</p><pre>def find_word(target_word: str, word_array: list[str]) -&gt; int:<br>  for i in range(len(word_array)):<br>    if word_array[i] == target_word:<br>      return i<br>  return -1</pre><p>It’s a pretty straightforward task, even for someone who’s only been coding for five minutes. But now, we want to measure how long it takes? For a small array with 10 or even 100 elements, it’ll be almost instant. But if the array has 100 million or even a billion elements, things get trickier.</p><p>How long do you think it will take for this code to run? When I say “how long”, I don’t mean in terms of actual time, because execution time depends on factors like your CPU, the version of Python you’re using, other programs running on your computer, and many other things unrelated to the algorithm itself. That would make it really inaccurate.</p><p>To answer this question, we use <em>asymptotic computational complexity </em>— or just “complexity” in everyday conversation.</p><p>I’m talking about an abstraction that works regardless of the computer you’re using. To measure this, we focus on the most resource-intensive operation in the algorithm — string comparison.</p><pre>current_word == desired_word</pre><p>So the real question is: how many times does this heaviest operation run?</p><p>Let’s imagine we have an array with 10 words. We also have a piece of code that searches for a word in the array.</p><pre>Word_array = [<br>    &quot;Apple&quot;,    # 1<br>    &quot;Baseball&quot;, # 2<br>    &quot;Banana&quot;,   # 3<br>    &quot;Cherry&quot;,   # 4<br>    &quot;Dragon&quot;,   # 5<br>    &quot;Elephant&quot;, # 6<br>    &quot;Giraffe&quot;,  # 7<br>    &quot;Monkey&quot;,   # 8<br>    &quot;Tiger&quot;,    # 9<br>    &quot;Zombie&quot;    # 10<br>]</pre><h4>Experiment 1</h4><p>Now, let’s say we’re looking for the word banana How many times do we compare strings? The correct answer is 3. First, we compare &quot;apple&quot; == &quot;banana&quot;— obviously, it’s False, so we move to the next word, &quot;baseball&quot; == &quot;banana&quot;— still no match, so we go to the next word, and finally, &quot;banana&quot; == &quot;banana&quot; gives True. We stop the loop and return the result.</p><h4>Experiment 2</h4><p>Let’s try finding the word applein the array. It’s the very first word. We start the loop, check if &quot;apple&quot; == &quot;apple&quot;, and then exit the function. Only 1 operation needed here.</p><h4>Experiment 3</h4><p>Now, let’s look for the word zombie. It’s the very last word. To find it, we have to go through the entire array, comparing it with every word, and only on the last iteration do we find the word and leave the array.</p><h3>Analysis:</h3><p>We can say that the algorithm’s execution time depends on two factors:</p><ol><li>The number of elements in the array.</li><li>There’s also some luck involved, depending on whether we find the desired word early or late in the array.</li></ol><p>Let’s introduce a variable <strong>n</strong> to represent the number of elements in the array. We’ll describe how the algorithm’s execution time depends on <strong>n</strong>.</p><p>This is where Big O notation comes in.</p><ul><li><strong>Best case:</strong> If we find the word on the first iteration, like apple in our example. In this case, we only need to perform one comparison, which is O(1).</li><li><strong>Worst case:</strong> If the word is at the end, like zombie, we have to check every element. In this case, we’d describe it as O(n), where <strong>n</strong> is the number of elements in the array (in this example, it’s 10).</li><li><strong>Average case:</strong> If we find the word somewhere in the middle, like monkey. On average, it’s between the best and worst cases: O(n/2) or just O(n).</li></ul><h4><strong>Why not O(10)?</strong></h4><p>The main idea of Big O notation is to show the <strong>dependency on input size</strong>, not to provide an exact time estimate. We care about the general pattern of the algorithm, not the exact number.</p><p>If you say an algorithm is O(10), it means the execution time would be the same for an array of size 100 and an array of size 100 million, which is obviously wrong.</p><p>In this example, the 10 comes from the current array size. If we increase the array size by 100 times, the number of iterations will also increase by 100 times. We show this dependency as O(n), which means the complexity scales with <strong>n</strong>, the size of the input.</p><h4>Scaling</h4><p>What if the array size isn’t 10, but 100? How does that affect our estimate?</p><p>It depends. Don’t rush to just multiply all numbers by 10. Sometimes it works, but usually not. You need to carefully examine the algorithm.</p><ul><li>In the <strong>best case</strong>, we find the element on the first try — so it’s still O(1), no matter if the array has 10 elements or 10 billion. We always meet the first word in the first iteration, so the execution time doesn’t depend on the array size. That’s why we don’t use the <strong>n</strong> variable here — there’s no dependency on the array size in the best case.</li><li>In the <strong>worst case</strong>, we find the element last. In our earlier example, with 10 elements (n=10), it took 10 iterations. With 100 elements (n=100), it would take 100. So in the worst case, we need <strong>n</strong> iterations, which gives us a complexity of O(n).</li><li>In the <strong>average case</strong>, we can still average the best and worst cases like before: O((1 + n)/2). Since <strong>n</strong> is often a large number, we simplify it to O(n). This follows similar rules to limit algebra when <strong>n</strong> approaches infinity.</li></ul><p>As a result, the <strong>average case</strong> complexity is O(n). In everyday language, this is called <strong>linear complexity</strong>, which is why the algorithm is known as a <strong>linear search</strong>.</p><p>What does O(n) really mean? It means we need about <strong>n</strong> heavy operations for an array of size <strong>n</strong>. If <strong>n</strong> is 100, we need 100 operations. If <strong>n</strong> is 10 billion, we need 10 billion operations to complete the task.</p><p>We can visualize how the execution time depends on <strong>n</strong> (the number of elements in the array).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ztZQgmVCzP3s7BxI" /></figure><h3>Non-linear Complexity</h3><p>We’re still working on the task of searching for words in an array of strings, but now we’ll try to solve it in a more efficient way.</p><p>We’re going to implement the <strong>binary search</strong> algorithm.</p><h4>What is binary search?</h4><p>How would you search for a word in a dictionary in real life? You probably wouldn’t flip through every page from the beginning — that would take forever.</p><p>If you don’t have a table of contents, you’d probably open the book somewhere in the middle, check the first letter on the page, and then decide: if the word you’re looking for starts with a letter that comes before this one, you’d open the middle of the first half of the book. If it comes after, you’d open the middle of the second half. You’d keep repeating this process, halving your search area each time, until you find the word.</p><p>That’s exactly how binary search works. Just remember, it only works if the array is sorted — just like you can’t use this method on a real book if it’s not alphabetically ordered.</p><p>Here’s the implementation:</p><pre>def binary_search(target_word: str, word_array: list[str]) -&gt; int:<br>    low = 0<br>    high = len(arr) - 1<br>    <br>    while low &lt;= high:<br>        mid = (low + high) // 2  # Find the middle index<br><br>        # Check if the target is at mid<br>        if arr[mid] == target:<br>            return mid  # Target found, return the index<br>        <br>        # If the target is smaller, search in the left half<br>        elif arr[mid] &gt; target:<br>            high = mid - 1<br>        <br>        # If the target is larger, search in the right half<br>        else:<br>            low = mid + 1<br>    <br>    return -1  # Target is not in the array</pre><p><strong>Explanation:</strong></p><p>In each loop iteration, we choose the middle element of the current section of the array. After checking whether the target word is in the left or right half of that section, we can reduce the search area by half, selecting the appropriate side.</p><p>For example, let’s say the array has 100 elements, and we’re looking for the 20th element.</p><ul><li><strong>First iteration:</strong> We divide the array in the middle — at the 50th element. The 20th element is to the left of the 50th, so we reduce the search to the first 50 elements.</li><li><strong>Second iteration:</strong> We divide the array again — now at the 25th element. The 20th element is still on the left, so we narrow the search to the first 25 elements.</li><li><strong>Third iteration:</strong> We divide the array again — this time at the 12th element. The 20th element is to the right of the 12th, so we now focus on the range between the 12th and 25th elements.</li><li><strong>Fourth iteration:</strong> The middle is now the 19th element. We choose the right side, between the 19th and 25th.</li><li><strong>Fifth iteration:</strong> The middle is the 22nd element. We narrow it down to the left, between the 19th and 22nd.</li><li><strong>Sixth iteration:</strong> The middle is the 21st element. Again, we go left, between the 19th and 20th.</li><li><strong>Seventh iteration:</strong> We have just two elements left — 19th and 20th — and we find the 20th element.</li></ul><p>In total, it took 7 iterations to find the desired element, compared to potentially 100 iterations if we were doing a linear search (checking each element one by one).</p><h4>Why 7 iterations?</h4><p>Because each iteration halves the search area. At the start, we’re uncertain among 100 elements. After the first iteration, we’re uncertain among 50, and so on. If you divide 100 by 2 six times, you get:</p><p>100 / 2 / 2 / 2 / 2 / 2 / 2 = 100 / 2⁶ ≈ 1.56.</p><p>At that point, we’re left with uncertainty between just two elements (since we round 1.56 up). Dividing one more time (the 7th iteration) removes the remaining uncertainty.</p><h4>Logarithmic complexity</h4><p>Mathematically, this relationship is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*CrMN55peuuAgdI7l.png" /></figure><p>Using this formula, we can calculate how many iterations it takes to find an element in a sorted array with binary search:</p><ul><li>For an array of 100 elements, log₂(100) is 7 (since ²⁷ is 128).</li><li>For an array of 1,000 elements, log₂(1000) is 10 (since ²¹⁰ is 1,024).</li></ul><p>This highlights the power of logarithmic complexity: when the number of elements in the array increases by 10 times, the number of iterations only increases by about 30%.</p><p>Does that sound unbelievable? Think back to the dictionary analogy: imagine trying to find a specific word by flipping through every page (linear search) versus dividing the book in half, over and over (binary search). With a small book, the difference is minor, but with a big book, the difference is huge.</p><h4><strong>Other Complexity Types</strong></h4><p>In this article, we’ve mainly discussed O(n) (linear) and O(log(n)) (logarithmic) complexities. But just for your information, keep in mind that there are many other types of complexities, such as:</p><ul><li>O(n²) — Quadratic</li><li>O(n^c) — Polynomial</li><li>O(c^n) — Exponential</li><li>O(n!) — Factorial</li></ul><p>And many more.</p><h3>Why Algorithm Choice Matters — Comparison Table</h3><p>Now, imagine you have an array of size <strong>n</strong> and an algorithm with one of the following complexity types: logarithmic, linear, or quadratic. How many iterations will you need to solve the task based on the algorithm’s complexity?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JEsOTTy5HZuXdKpkoiG4Bg.png" /><figcaption>Table: difference between logarithmic, linear and quadratic scaling</figcaption></figure><p><strong>Instead of a conclusion:</strong></p><p>Imagine that each operation takes 1 second to execute in real time. Now, compare the estimated time duration for the values in the table above in terms of seconds, hours, and days. Notice how quickly performance degrades as the array size increases.</p><p>Next chapter: <a href="https://medium.com/@nickshpilevoy/quadratic-time-complexity-86f81e57e54e">https://medium.com/@nickshpilevoy/quadratic-time-complexity-86f81e57e54e</a></p><p>Subscribe if you’d like to be notified when the next chapter is out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ac8ba83d7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Higher Education Required for a Quant?]]></title>
            <link>https://medium.com/@nickshpilevoy/is-higher-education-required-for-a-quant-7429bd16e615?source=rss-279e59a6d2ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/7429bd16e615</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[quant]]></category>
            <dc:creator><![CDATA[Nikita Shpilevoy]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 20:46:36 GMT</pubDate>
            <atom:updated>2024-07-02T20:46:36.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2QziEDTNoSuERUu5" /><figcaption>AI-generated image</figcaption></figure><p>I analyzed the first 1000 Financial Quantitative Analyst/Researcher positions on Indeed (automatically, of course) and gathered the following statistics:</p><ul><li>637 require higher education (63.7%). Of those, 319 mention an MSc or PhD. 422 mention a preference for STEM fields such as physics, mathematics, computer science, etc.</li><li>The remaining 36.3% of jobs do not specify a higher education requirement.</li></ul><p>Is it promising that over a third of these jobs allow you to apply without a diploma?</p><p>In reality, it is not. Many employers don’t state this explicitly because they assume it, and they will reject candidates without the expected education listed on their CV.</p><p>That sounds sad, doesn’t it?</p><p>But there’s good news: some employers do care about your skills rather than just your diploma, though they are few. However, your success depends on two things:</p><ol><li>Your actual skills</li><li>Your persistence</li></ol><p>Persistence, as a personal trait and soft skill, isn’t the focus of this blog.</p><p>But how do you get the hard skills without higher education? Where will you learn mathematics and statistics? The most obvious answer is university, which brings us back to the starting point: you need to go to university.</p><p>Is it possible to learn on your own? Sure. Just find any university program, get the books, and start solving problems. You can even self-examine or hire a tutor for it. It may yield better results than what 90% of universities provide, especially if you’re in a developing country.”</p><p>However, there are two problems with this approach:</p><ol><li>You must be highly responsible and self-motivated to achieve the equivalent of higher education independently. Many people don’t have enough willpower and will just drop it halfway.</li><li>You don’t get a diploma as confirmation of your knowledge. This creates a problem in the job search as discussed above. This means that after solving the first problem — learning the required skills — you face another challenge: getting a job without any formal confirmation of your skills.</li></ol><p>However, a university diploma is not the only way to prove your skills. There are many certifications like CFA, CQF, etc. These are highly valued in the financial field. Nothing stops you from preparing for and passing the exams. However, companies may still prefer candidates who have higher education.</p><p><strong>In conclusion</strong>, is it possible to become a quant without higher education? Yes. I can confidently state this as someone who got their first quant job without any diploma or certification.</p><p>Is it worth it? No. If there are two ways with the same result but one of them is much simpler, why choose the harder one? However, if this is the path you choose for any reason, refer to the first answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7429bd16e615" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>