<?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 Prasham Pahadiya on Medium]]></title>
        <description><![CDATA[Stories by Prasham Pahadiya on Medium]]></description>
        <link>https://medium.com/@prashampahadiya9228?source=rss-69dec8386472------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-TUI7J9m3zzcdJap.jpg</url>
            <title>Stories by Prasham Pahadiya on Medium</title>
            <link>https://medium.com/@prashampahadiya9228?source=rss-69dec8386472------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:41:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashampahadiya9228/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[Finding the Lowest Common Ancestor (LCA) in a Binary Tree: A Simple Approach]]></title>
            <link>https://medium.com/@prashampahadiya9228/finding-the-lowest-common-ancestor-lca-in-a-binary-tree-a-simple-approach-671abec2808f?source=rss-69dec8386472------2</link>
            <guid isPermaLink="false">https://medium.com/p/671abec2808f</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[lowest-common-ancestor]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Prasham Pahadiya]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 11:52:44 GMT</pubDate>
            <atom:updated>2025-04-28T11:53:51.391Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Lowest Common Ancestor (LCA)</strong> problem is a classic question in Data Structures and Algorithms (DSA). It’s widely asked in technical interviews and is an essential concept when working with trees. In this post, we’ll walk through the problem, explain the logic behind it step by step, and solve it using Python.</p><p>Let’s break it down in simple terms and make it as interactive as possible. Ready? Let’s dive in! 🏊‍♂️</p><h3>Problem Understanding</h3><p>In the <strong>LCA of a Binary Tree</strong> problem, you are given a <strong>binary tree</strong> and two nodes, <strong>p</strong> and <strong>q</strong>. Your task is to find the <strong>lowest common ancestor</strong> of these two nodes.</p><h3>What is the Lowest Common Ancestor?</h3><p>The <strong>LCA</strong> of two nodes, say <strong>p</strong> and <strong>q</strong>, in a binary tree is defined as the lowest node in the tree that has both <strong>p</strong> and <strong>q</strong> as descendants (either <strong>p</strong> or <strong>q</strong> can also be a descendant of the LCA).</p><h4>Example:</h4><p>Let’s consider the following binary tree:</p><pre>        3<br>       / \<br>      5   1<br>     / \ / \<br>    6  2 0  8<br>      / \<br>     7   4</pre><p>In this tree:</p><ul><li>The LCA of nodes <strong>5</strong> and <strong>1</strong> is <strong>3</strong>, because <strong>3</strong> is the lowest node that has both <strong>5</strong> and <strong>1</strong> as descendants.</li><li>The LCA of nodes <strong>5</strong> and <strong>4</strong> is <strong>5</strong>, because <strong>4</strong> is a descendant of <strong>5</strong>.</li></ul><h3>Step-by-Step Thought Process</h3><p>Before jumping into the code, let’s break down the problem and try to think about it logically:</p><h4>Step 1: What to Look For?</h4><p>The goal of this step is to identify the conditions that help us determine when a node is the <strong>LCA</strong> of the two nodes <strong>p</strong> and <strong>q</strong>.</p><p>Let’s consider a binary tree and walk through <strong>four possible scenarios</strong>. In each scenario, we will analyze where <strong>p</strong> and <strong>q</strong> are located, and how that affects the decision-making process.</p><ul><li>We need to check if both the left and right subtrees of a node contain one of the nodes (<strong>p</strong> or <strong>q</strong>).</li><li>If we find both <strong>p</strong> and <strong>q</strong> in different subtrees of a node, then <strong>this node is the LCA</strong>.</li></ul><p>Let’s look at a few key scenarios:</p><p><strong>Scenario 1: Both p and q are found in the left subtree.</strong></p><pre>        3<br>       / \<br>      5   1<br>     / \<br>    6   2<br>        / \<br>       7   4<br></pre><p>Now, assume <strong>p = 6</strong> and <strong>q = 7</strong>.</p><ul><li>Both <strong>p</strong> and <strong>q</strong> (6 and 7) are in the <strong>left subtree</strong> of the root node <strong>3</strong>.</li><li>As we search, we’ll find that both <strong>6</strong> and <strong>7</strong> are in the <strong>left subtree</strong> of <strong>5</strong> (which is the left child of the root node).</li><li><strong>5</strong> becomes the <strong>LCA</strong> in this case because it’s the lowest node that contains both <strong>6</strong> and <strong>7</strong> in its subtree.</li></ul><p><strong>Scenario 2: Both p and q are found in the right subtree.</strong></p><pre>        3<br>       / \<br>      5   1<br>         / \<br>        0   8</pre><p>Let’s assume <strong>p = 1</strong> and <strong>q = 8</strong>.</p><ul><li>Both <strong>p</strong> and <strong>q</strong> (1 and 8) are in the <strong>right subtree</strong> of the root node <strong>3</strong>.</li><li>We can see that <strong>1</strong> and <strong>8</strong> are both under the right child of <strong>3</strong>, so the <strong>LCA</strong> is <strong>1</strong>, as <strong>8</strong> is in its right subtree.</li></ul><p><strong>Scenario 3: One of p or q is in the left subtree and the other is in the right subtree.</strong></p><pre>        3<br>       / \<br>      5   1<br>     / \<br>    6   2<br>        / \<br>       7   4</pre><p>Now, assume <strong>p = 6</strong> and <strong>q = 8</strong>.</p><ul><li><strong>p = 6</strong> is in the <strong>left subtree</strong> (under node <strong>5</strong>).</li><li><strong>q = 8</strong> is in the <strong>right subtree</strong> (under node <strong>1</strong>).</li></ul><p>Here’s what happens:</p><ul><li>While traversing, we’ll find that <strong>6</strong> is in the left subtree and <strong>8</strong> is in the right subtree of node <strong>3</strong>.</li><li>This means that the <strong>LCA</strong> is <strong>3</strong> because <strong>3</strong> is the first node where <strong>p</strong> (6) and <strong>q</strong> (8) are in <strong>different subtrees</strong> — one on the left and one on the right.</li></ul><p><strong>Scenario 4: Only one of p or q is found in the current node’s subtree, the other is either in its left or right subtree.</strong></p><pre>        3<br>       / \<br>      5   1<br>     / \<br>    6   2<br>        / \<br>       7   4</pre><p>Let’s assume <strong>p = 7</strong> and <strong>q = 5</strong>.</p><ul><li><strong>p = 7</strong> is in the <strong>left subtree</strong> of node <strong>2</strong>, and <strong>q = 5</strong> is located in the <strong>left subtree</strong> of the root node <strong>3</strong>.</li><li>The recursion would find that <strong>p = 7</strong> is in <strong>5’s</strong> left subtree, and <strong>q = 5</strong> itself is the ancestor of <strong>7</strong>.</li><li>In this case, <strong>5</strong> becomes the <strong>LCA</strong> because <strong>7</strong> is a descendant of <strong>5</strong>. This case works because <strong>5</strong> has <strong>7</strong> as a direct descendant, and <strong>p = 7</strong> is effectively a child of <strong>q = 5</strong>.</li></ul><blockquote><strong><em>Recap of Key Points:</em></strong></blockquote><blockquote><strong><em>LCA is determined by the relationship between the subtrees</em></strong><em>:</em></blockquote><blockquote>If both <strong>p</strong> and <strong>q</strong> are found in the <strong>left subtree</strong>, the LCA is somewhere in the <strong>left subtree</strong>.</blockquote><blockquote>If both are found in the <strong>right subtree</strong>, the LCA is somewhere in the <strong>right subtree</strong>.</blockquote><blockquote><strong><em>The core idea</em></strong><em>:</em></blockquote><blockquote>If <strong>p</strong> and <strong>q</strong> are found in <strong>different subtrees</strong> (left and right), the current node is the LCA because it’s the common ancestor that connects both subtrees.</blockquote><blockquote><strong><em>A special case</em></strong><em>:</em></blockquote><blockquote>If <strong>p</strong> or <strong>q</strong> is a descendant of the other (meaning one node is in the subtree of the other), the LCA will be the node where the ancestor starts the search. For example, in <strong>Scenario 4</strong>, <strong>5</strong> is the ancestor of <strong>7</strong>, so <strong>5</strong> becomes the LCA.</blockquote><blockquote><strong><em>How Does This Help in Our Recursive Approach?</em></strong></blockquote><blockquote>In the recursive function, we follow these rules:</blockquote><blockquote><strong>Base case</strong>: If the current node is None, return None. If the node is either <strong>p</strong> or <strong>q</strong>, return that node.</blockquote><blockquote><strong>Recursive case</strong>: We search the left and right subtrees:</blockquote><blockquote>If both left and right recursive calls return non-None nodes, we know that the current node is the <strong>LCA</strong>.</blockquote><blockquote>If one of the recursive calls returns a non-None node, we return that node (because it contains either <strong>p</strong> or <strong>q</strong>).</blockquote><h4>Step 2: Key Insight</h4><p>If we find both <strong>p</strong> and <strong>q</strong> in both the <strong>left</strong> and <strong>right</strong> subtrees of a node, it’s a sure sign that the current node is their <strong>lowest common ancestor</strong>.</p><p>If only one of the nodes is in the left or right subtree, we continue our search in that direction.</p><h4>Step 3: Recursive Nature of the Problem</h4><p>This problem can be solved recursively. We check for the presence of <strong>p</strong> and <strong>q</strong> in both the left and right subtrees and return the node where both are found or whichever node contains <strong>p</strong> or <strong>q</strong>.</p><h4>Step 4: Base Case</h4><p>The base case for our recursion is simple:</p><ul><li>If the current node is <strong>None</strong>, we return None (since there&#39;s no ancestor here).</li><li>If the current node is either <strong>p</strong> or <strong>q</strong>, we return that node.</li></ul><h3>Solution Code in Python</h3><p>Let’s now put our thoughts into code. Below is the Python implementation of the <strong>LCA of a Binary Tree</strong>:</p><pre># Definition for a binary tree node.<br>class TreeNode:<br>    def __init__(self, val=0, left=None, right=None):<br>        self.val = val<br>        self.left = left<br>        self.right = right<br><br>class Solution:<br>    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -&gt; TreeNode:<br>        # Base case: If the current node is None or equals to p or q, return it<br>        if not root or root == p or root == q:<br>            return root<br>        <br>        # Recursively search in the left subtree<br>        left = self.lowestCommonAncestor(root.left, p, q)<br>        <br>        # Recursively search in the right subtree<br>        right = self.lowestCommonAncestor(root.right, p, q)<br>        <br>        # If both left and right are not None, current node is the LCA<br>        if left and right:<br>            return root<br>        <br>        # Otherwise, return the non-None node (either left or right)<br>        return left if left else right</pre><h3>Explanation of the Code</h3><p>Let’s go through the code step by step:</p><ol><li><strong>TreeNode Class</strong>: This class defines the structure of each node in the binary tree, with val, left, and right attributes.</li><li><strong>Base Case</strong>: If the current node is None, we return None. If the current node is <strong>p</strong> or <strong>q</strong>, we return that node as the potential ancestor.</li><li><strong>Recursive Search</strong>:</li></ol><ul><li>We first recursively search the <strong>left</strong> subtree for <strong>p</strong> or <strong>q</strong>.</li><li>We then recursively search the <strong>right</strong> subtree for <strong>p</strong> or <strong>q</strong>.</li></ul><p><strong>4. Determining the LCA</strong>:</p><ul><li>If both <strong>left</strong> and <strong>right</strong> subtrees return a node (i.e., both <strong>p</strong> and <strong>q</strong> are found in different subtrees), then the current node is the <strong>LCA</strong>.</li><li>If only one subtree returns a node, we know that the LCA is found in that subtree, so we return the non-None node (either <strong>left</strong> or <strong>right</strong>).</li></ul><h3>Time Complexity</h3><p>The time complexity of this solution is <strong>O(n)</strong>, where <strong>n</strong> is the number of nodes in the binary tree. This is because, in the worst case, we might have to visit each node once.</p><h3>Interactive Example</h3><p>Let’s consider a simple binary tree for an interactive demonstration:</p><pre>        3<br>       / \<br>      5   1<br>     / \ / \<br>    6  2 0 8<br>      / \<br>     7   4</pre><ul><li>Let’s say <strong>p = 5</strong> and <strong>q = 1</strong>.</li><li>The LCA of <strong>5</strong> and <strong>1</strong> is <strong>3</strong>, since it’s the lowest node that has both <strong>5</strong> and <strong>1</strong> as descendants.</li><li>For <strong>p = 5</strong> and <strong>q = 4</strong>, the LCA is <strong>5</strong>, because <strong>4</strong> is a descendant of <strong>5</strong>.</li></ul><h3>Conclusion</h3><p>The <strong>LCA of a Binary Tree</strong> problem is an interesting and important problem in tree data structures. By breaking down the problem step-by-step, we can easily identify the common ancestor of two nodes using recursion. The key to solving this problem is understanding how to leverage the binary tree structure and using the base case effectively.</p><p>Feel free to experiment with different tree structures and values of <strong>p</strong> and <strong>q</strong> to solidify your understanding!</p><p>If you have any questions or suggestions, feel free to leave a comment. Happy coding! 🚀</p><p>#LCA #BinaryTree #DSA #Python #Coding #TechInterview</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671abec2808f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SYSTEM DESIGN GENERIC INTERVIEW CONSIDERATIONS]]></title>
            <link>https://medium.com/@prashampahadiya9228/system-design-generic-interview-considerations-c17a474df264?source=rss-69dec8386472------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17a474df264</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Prasham Pahadiya]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 07:36:24 GMT</pubDate>
            <atom:updated>2025-04-16T07:36:24.440Z</atom:updated>
            <content:encoded><![CDATA[<p>When revisiting requirements and confirming assumptions during follow-up questions in a system design interview, it’s crucial to be methodical and strategic. Here’s a breakdown of factors to consider when asking clarifying questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*TLVObRi5q3D2udJn4_uQVQ.png" /></figure><h3>1. Scope of the System</h3><ul><li><strong>Does the scope change?</strong>: Often, follow-up questions will introduce new components or extend the system’s capabilities (e.g., adding features like user authentication, supporting additional platforms, or introducing new stakeholders). Ensure you understand whether you’re being asked to design a more complex system or a different aspect of the same system.</li><li><strong>Are there additional constraints?</strong>: Ask if there are any limits on resources, such as CPU, memory, or database size. You might also want to inquire about the number of users, expected traffic, or data volume the system must handle.</li></ul><h3>2. Functional vs. Non-Functional Requirements</h3><ul><li><strong>New Functionalities</strong>: If the follow-up question adds features (like user recommendations, messaging, or notifications), clarify how these features should work within the existing design and whether they change the flow or key components.</li><li><strong>Non-Functional Aspects</strong>: Focus on scalability, reliability, and performance. Ask about acceptable latencies, fault tolerance, and availability needs. For example, “What’s the expected downtime tolerance?” or “How critical is real-time processing for this system?”</li></ul><h3>3. User and Usage Context</h3><ul><li><strong>Who are the users?</strong>: Understand if the follow-up asks for a design that caters to different user personas. For example, is the system meant for end users, admins, or both?</li><li><strong>Usage Patterns</strong>: Inquire about the usage patterns — will there be high spikes in traffic or is usage more predictable? Do users need to access the system simultaneously, or is usage spread over time?</li></ul><h3>4. Scale and Growth</h3><ul><li><strong>Current and Future Scale</strong>: Ask about the expected growth rate of the system. If the system should handle millions of users now but scale to billions later, you need to adjust your design accordingly. Questions like, “What’s the target user base for the first year?” or “How do we expect traffic to grow over the next 3 years?” can help.</li><li><strong>Data Growth</strong>: Will the data grow rapidly (e.g., logs, transactions)? Confirm the expected volume of data and how it should be stored and accessed over time.</li></ul><h3>5. Availability and Reliability</h3><ul><li><strong>Service Availability</strong>: For services that must be available 24/7, ask what the acceptable downtime is, or what level of availability is required (e.g., 99.9%, 99.99%).</li><li><strong>Failure Handling</strong>: How should the system handle outages or service failures? Should it fail gracefully? Is there a need for data recovery, or should the system simply ignore partial failures?</li></ul><h3>6. Consistency and Latency Requirements</h3><ul><li><strong>Consistency vs. Availability</strong>: Ask how strict the consistency needs to be. For example, “Does the system require strong consistency, or would eventual consistency be acceptable for some parts of the system?”</li><li><strong>Performance and Latency</strong>: Clarify latency requirements. For example, if you’re building a search service, do they need results in 100ms, 1s, or is a few seconds acceptable?</li></ul><h3>7. Security and Compliance</h3><ul><li><strong>Security Needs</strong>: If the follow-up introduces sensitive data (e.g., PII), confirm how much emphasis should be placed on encryption, access controls, and auditing. You might ask, “What level of encryption is required?” or “Do we need to comply with regulations like GDPR?”</li><li><strong>Regulatory Compliance</strong>: Are there any industry regulations the system needs to adhere to? For example, in healthcare or finance, there might be constraints around data retention or security measures.</li></ul><h3>8. Cost and Budget Constraints</h3><ul><li><strong>Budget Limitations</strong>: If relevant, ask about the budget for infrastructure or cloud costs. A cost-effective design might prioritize simpler solutions over complex but expensive ones.</li><li><strong>Trade-offs Between Cost and Performance</strong>: Explore if the system can tolerate cost-cutting measures like reduced redundancy or less performance, or whether performance should always be prioritized.</li></ul><h3>9. External Dependencies</h3><ul><li><strong>Third-party Services</strong>: Clarify any reliance on third-party APIs, services, or integrations. For instance, “Does the system integrate with any existing services or databases?” or “Are we depending on any external APIs?”</li><li><strong>Data Ownership and Legal Constraints</strong>: Be aware of who owns the data, and if there are any restrictions on how data should be handled, stored, or transferred.</li></ul><h3>10. Deployment and Maintenance</h3><ul><li><strong>Deployment Environment</strong>: Is the system intended to run on cloud infrastructure (AWS, GCP, Azure) or on-premises? Does the system need to be multi-cloud or hybrid?</li><li><strong>Maintenance and Upgrades</strong>: Ask about the lifecycle of the system, how often it will need to be updated or patched, and what uptime guarantees are necessary for maintenance windows.</li></ul><h3>11. Monitoring and Analytics</h3><ul><li><strong>Metrics and Logging</strong>: Does the system need to include monitoring or logging components? How detailed should the logs be? You can ask, “What key metrics should we track to ensure system health?”</li><li><strong>Real-time Analytics</strong>: Will the system need to process and visualize data in real-time (e.g., for analytics dashboards)?</li></ul><h3>12. Cost vs. Time</h3><ul><li><strong>Speed of Development</strong>: How quickly do you need to deliver the system? If time is more important than perfect architecture, you might need to trade off scalability for faster time-to-market.</li><li><strong>Long-Term Maintenance</strong>: Would the system’s long-term maintainability be a concern if you prioritize a simpler approach during initial development?</li></ul><h3>Example Follow-up Questions to Ask:</h3><ul><li><strong>Scope/Feature Clarification</strong>: “You mentioned adding a notification system — should this system handle notifications for both mobile and email users, or just one?”</li><li><strong>Scaling</strong>: “How many users do we anticipate interacting with this service concurrently? Should the design support spikes in traffic, such as during promotions?”</li><li><strong>Consistency</strong>: “Are there any parts of the system that can tolerate eventual consistency, or should everything be strongly consistent?”</li><li><strong>Latency/Performance</strong>: “What are the performance targets in terms of response time or throughput? Are there any parts of the system where low latency is critical?”</li><li><strong>Security/Compliance</strong>: “Does this system handle sensitive user data? Should encryption be implemented at rest, in transit, or both?”</li><li><strong>External Systems</strong>: “Is the system expected to integrate with any third-party APIs or services, and if so, what SLAs do we need to adhere to?”</li></ul><p>By keeping these factors in mind, you ensure you’re asking the right questions that help refine and clarify the design problem in a structured way. It also shows the interviewer you’re thoughtful about how to adapt to changing requirements and can take a systems-thinking approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17a474df264" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Classes and Abstract Methods in Python]]></title>
            <link>https://medium.com/@prashampahadiya9228/abstract-classes-and-abstract-methods-in-python-e632ea34bc79?source=rss-69dec8386472------2</link>
            <guid isPermaLink="false">https://medium.com/p/e632ea34bc79</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Prasham Pahadiya]]></dc:creator>
            <pubDate>Fri, 31 May 2024 12:44:40 GMT</pubDate>
            <atom:updated>2024-05-31T12:44:40.125Z</atom:updated>
            <content:encoded><![CDATA[<p>Abstract classes and abstract methods in Python are fundamental concepts in object-oriented programming that facilitate the design of a base class, which cannot be instantiated on its own but can be used as a blueprint for other classes. Here’s an overview:</p><p><strong>Abstract Classes</strong><br>An abstract class is a class that is meant to be subclassed but not instantiated directly. It can include one or more abstract methods. In Python, abstract classes are created using the `abc` module, specifically the `ABC` class.</p><p><strong>Abstract Methods</strong><br>An abstract method is a method that is declared in an abstract class but does not have an implementation. Subclasses of the abstract class are required to implement these abstract methods.</p><h3>How to Define and Use Abstract Classes and Methods</h3><ol><li>Import the `abc` module:</li></ol><pre>from abc import ABC, abstractmethod</pre><p>2. Create an abstract class by inheriting from `ABC`:</p><pre>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        pass<br>    @abstractmethod<br>    def perimeter(self):<br>        pass</pre><p>3. Implement the abstract class in a subclass:</p><pre>class Rectangle(Shape):<br>    def __init__(self, width, height):<br>        self.width = width<br>        self.height = height<br>    def area(self):<br>        return self.width * self.height<br>    def perimeter(self):<br>        return 2 * (self.width + self.height)</pre><p>4. Instantiate the subclass and use its methods:</p><pre>rectangle = Rectangle(10, 5)<br>print(f&quot;Area: {rectangle.area()}&quot;)        # Output: Area: 50<br>print(f&quot;Perimeter: {rectangle.perimeter()}&quot;)  # Output: Perimeter: 30</pre><h3>Why Use Abstract Classes and Methods</h3><ol><li><strong>Enforcing a Contract</strong>:</li></ol><p>Abstract classes and methods ensure that any subclass provides implementations for the specified methods, thus enforcing a certain design contract.</p><p>Abstract classes and methods enforce a contract by ensuring that any subclass provides implementations for the specified methods.**</p><p>When you define an abstract class with abstract methods, you are essentially creating a blueprint for other classes. This ensures that any subclass will implement the methods you expect. This is useful for maintaining a consistent interface across different implementations.</p><p>Example:</p><pre>from abc import ABC, abstractmethod<br>class PaymentProcessor(ABC):<br>    @abstractmethod<br>    def authorize(self):<br>        pass<br>    <br>    @abstractmethod<br>    def capture(self):<br>        pass<br>class CreditCardProcessor(PaymentProcessor):<br>    def authorize(self):<br>        print(&quot;Authorizing credit card&quot;)<br>    <br>    def capture(self):<br>        print(&quot;Capturing credit card payment&quot;)<br>class PayPalProcessor(PaymentProcessor):<br>    def authorize(self):<br>        print(&quot;Authorizing PayPal payment&quot;)<br>    <br>    def capture(self):<br>        print(&quot;Capturing PayPal payment&quot;)</pre><p>Here, both `CreditCardProcessor` and `PayPalProcessor` are guaranteed to have `authorize` and `capture` methods, ensuring a consistent interface.</p><p>2. <strong>Code Reusability</strong>:<br> They promote code reusability by allowing common functionality to be defined in the abstract class and specific functionality in the subclasses.</p><p>You can define methods with common behavior in the abstract class, which can then be inherited by subclasses. This avoids code duplication and promotes reuse of common code.</p><p>Example:</p><pre>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        pass<br>    @abstractmethod<br>    def perimeter(self):<br>        pass<br>    def describe(self):<br>        print(f&quot;This shape has an area of {self.area()} and a perimeter of {self.perimeter()}.&quot;)<br>class Rectangle(Shape):<br>    def __init__(self, width, height):<br>        self.width = width<br>        self.height = height<br>    def area(self):<br>        return self.width * self.height<br>    def perimeter(self):<br>        return 2 * (self.width + self.height)</pre><p>The `describe` method is reusable by any subclass of `Shape`, avoiding the need to implement it in each subclass.</p><p>3. <strong>Design Clarity:</strong><br> They help in creating a clear and logical class hierarchy, making it easier to understand and maintain the code.</p><p>By using abstract classes, you can create a clear separation between the general concept (abstract class) and specific implementations (subclasses). This makes your codebase more organized and easier to navigate.</p><p>Example:</p><pre>class Vehicle(ABC):<br>    @abstractmethod<br>    def start_engine(self):<br>        pass<br>class Car(Vehicle):<br>    def start_engine(self):<br>        print(&quot;Starting car engine&quot;)<br>class Motorcycle(Vehicle):<br>    def start_engine(self):<br>        print(&quot;Starting motorcycle engine&quot;)</pre><p>This hierarchy clearly shows the relationship between `Vehicle`, `Car`, and `Motorcycle`, making it clear that both `Car` and `Motorcycle` are types of vehicles with their own implementations of `start_engine`.</p><p>4. <strong>Polymorphism:</strong><br> They enable polymorphism by allowing objects to be treated as instances of the abstract class, even if they are instances of a subclass that provides specific implementations of the abstract methods.</p><p>Polymorphism allows you to write code that works on the abstract class level, treating all subclasses uniformly. This is powerful for writing flexible and reusable code.</p><p>Example:</p><pre>def process_payment(payment_processor: PaymentProcessor):<br>    payment_processor.authorize()<br>    payment_processor.capture()<br>credit_card = CreditCardProcessor()<br>paypal = PayPalProcessor()<br>process_payment(credit_card)  # Works with CreditCardProcessor<br>process_payment(paypal)       # Works with PayPalProcessor</pre><p>In this example, `process_payment` can accept any object that is an instance of `PaymentProcessor`, allowing for flexible and reusable code that can handle different types of payment processors.</p><h3>Example with More Context</h3><p>Suppose you are designing a system for different types of payment methods. You could define an abstract class `Payment` with abstract methods like `authorize_payment` and `process_payment`.</p><pre>from abc import ABC, abstractmethod<br><br>class Payment(ABC):<br>    @abstractmethod<br>    def authorize_payment(self):<br>        pass<br><br>    @abstractmethod<br>    def process_payment(self):<br>        pass<br><br>class CreditCardPayment(Payment):<br>    def authorize_payment(self):<br>        print(&quot;Authorizing credit card payment.&quot;)<br>        <br>    def process_payment(self):<br>        print(&quot;Processing credit card payment.&quot;)<br><br>class PayPalPayment(Payment):<br>    def authorize_payment(self):<br>        print(&quot;Authorizing PayPal payment.&quot;)<br>        <br>    def process_payment(self):<br>        print(&quot;Processing PayPal payment.&quot;)<br><br></pre><p>In this example, `CreditCardPayment` and `PayPalPayment` are subclasses that implement the abstract methods of the `Payment` abstract class. This design ensures that any payment method must provide its own implementation of authorization and processing.</p><h3>How Abstract Classes Promote Resuability</h3><p>Abstract classes and methods promote reusability in several ways:</p><p>1. Common Interface<br>Abstract classes define a common interface that multiple subclasses can implement. This ensures that any subclass adhering to this interface can be used interchangeably, promoting reusability of the higher-level code that relies on the abstract interface rather than specific implementations.</p><p>2. Base Functionality<br>Abstract classes can include concrete methods (methods with implementations) in addition to abstract methods. This allows the abstract class to provide shared functionality that can be reused by all subclasses. Subclasses can inherit this functionality and extend or override it as needed.</p><p>3. Encapsulation of Shared Behavior<br>When common behavior is encapsulated in an abstract class, it avoids code duplication. Subclasses inherit this common behavior, ensuring that shared logic is written once and reused across multiple subclasses.</p><h4>Example of Reusability</h4><p>Consider a more detailed example where we have an abstract class for different types of shapes:</p><pre>from abc import ABC, abstractmethod<br>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        pass<br>    @abstractmethod<br>    def perimeter(self):<br>        pass<br>    def describe(self):<br>        print(f&quot;This shape has an area of {self.area()} and a perimeter of {self.perimeter()}.&quot;)<br>class Rectangle(Shape):<br>    def __init__(self, width, height):<br>        self.width = width<br>        self.height = height<br>    def area(self):<br>        return self.width * self.height<br>    def perimeter(self):<br>        return 2 * (self.width + self.height)<br>class Circle(Shape):<br>    def __init__(self, radius):<br>        self.radius = radius<br>    def area(self):<br>        import math<br>        return math.pi * self.radius ** 2<br>    def perimeter(self):<br>        import math<br>        return 2 * math.pi * self.radius</pre><h4>Key Points of Reusability:</h4><p>1. Shared Methods:The `describe` method in the `Shape` abstract class provides a common behavior for describing the shape. This method can be reused by any subclass without needing to redefine it.</p><p>2. Consistent Interface: The `area` and `perimeter` methods define a consistent interface. Any code that works with shapes can rely on these methods, making it easy to add new types of shapes without changing the higher-level code.</p><p>3. Avoiding Duplication: By placing common functionality in the abstract class, we avoid having to write the same method multiple times in each subclass. For example, the `describe` method is defined once in the `Shape` class but can be used by both `Rectangle` and `Circle`.</p><h4>Benefits of Reusability:</h4><p>- Maintainability: Changes to shared behavior need to be made only once in the abstract class rather than in each subclass.<br>- Extensibility: New subclasses can be added easily by inheriting from the abstract class and implementing the required abstract methods.<br>- DRY Principle: The &quot;Don&#39;t Repeat Yourself&quot; principle is adhered to, reducing redundancy and the potential for errors.</p><h3>Conclusion</h3><p>Abstract classes and methods are powerful tools in Python for creating a clear, maintainable, and extendable object-oriented design. They help enforce a certain structure in the code, promote reusability, and ensure that subclasses adhere to a defined interface. By using abstract classes, you create a clear, reusable structure that allows for flexible and maintainable code, making it easier to manage and extend in the long run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e632ea34bc79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>