<?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 Danial Khan on Medium]]></title>
        <description><![CDATA[Stories by Danial Khan on Medium]]></description>
        <link>https://medium.com/@khandanial114?source=rss-83070a447005------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aESMXOwIFLZyoPv5x9qrqQ.jpeg</url>
            <title>Stories by Danial Khan on Medium</title>
            <link>https://medium.com/@khandanial114?source=rss-83070a447005------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:05:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khandanial114/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[From Code to Combat: Space Invaders Game Tutorial Using Python and Pygame]]></title>
            <link>https://medium.com/@khandanial114/from-code-to-combat-space-invaders-game-tutorial-using-python-and-pygame-164526801881?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/164526801881</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 20:18:17 GMT</pubDate>
            <atom:updated>2025-06-15T20:18:17.126Z</atom:updated>
            <content:encoded><![CDATA[<p>🎮 <strong>Why Space Invaders?</strong></p><p>I chose Space Invaders because it’s one of the most iconic arcade games ever made simple in concept, yet incredibly engaging. The core mechanics (player movement, shooting, wave-based enemies, and score tracking) provide a perfect foundation for learning game development with <strong>Python and Pygame</strong>. It’s beginner-friendly, yet still complex enough to explore game loops, collision detection, sprite management, and event handling.</p><p>🤖 <strong>Effective Prompting Techniques I Discovered</strong></p><p>Working with AI to build Space Invaders taught me that <strong>how you phrase a prompt really matters</strong>. I quickly learned that clear, specific prompts produced far better results than vague or broad requests.</p><h3>✅ 1. Be Specific About the Outcome</h3><p>Early on, I asked things like:</p><blockquote>“Make aliens move like in the original game.”<em><br> …but this gave me mixed results. When I changed it to:<br> </em>“Write a function that moves a grid of aliens horizontally, and makes them move down when they reach the screen edge”<em><br> I got a clean, reusable solution that worked exactly as expected.</em></blockquote><h3>✅ 2. Break Problems Into Smaller Pieces</h3><p>Instead of asking:</p><blockquote>“Make the full game with player, bullets, and enemies,”</blockquote><p>I asked:</p><blockquote>“How to shoot bullets in Pygame and remove them when they leave the screen?”</blockquote><blockquote>“Detect collision between a bullet and an alien sprite.”</blockquote><blockquote>“Draw player lives and update when hit.”</blockquote><p>This made debugging easier and let me test each part independently.</p><p>🧩 <strong>How AI Handled Classic Programming Challenges</strong></p><p>One of the biggest hurdles I anticipated was <strong>group alien movement</strong>: coordinating multiple enemies so they move together, reverse direction at screen edges, and descend step-by-step.</p><p>With a single prompt, the AI generated an elegant approach that looped through a 2D list of aliens, applied horizontal velocity to all of them, and checked if any alien hit the screen edge to reverse direction and descend. This saved hours of trial and error.</p><p>Collision detection was another tricky area especially making sure bullets disappeared at the right time, and the game didn’t crash with “index out of range” errors. Instead of wrestling with logic bugs, I could just ask the AI to “write a bullet-alien collision function with proper removal from lists,” and it delivered working code using pygame.Rect and colliderect().</p><p>⚙️ <strong>Development Automation that Saved Time</strong></p><p>One of the biggest time-savers was having AI generate <strong>boilerplate Pygame setup code</strong>. From initialising the screen, setting the game loop, to loading images it handled all of this instantly. Instead of manually writing the setup every time, I could just focus on building game logic.</p><p>I also used AI to automate necessary parts, such as:</p><ul><li><strong>Bullet object creation and management</strong> (e.g., tracking when bullets should be removed from the screen).</li><li><strong>Drawing UI elements</strong> like score and lives using pygame.font, without digging through documentation.</li><li><strong>Frame rate control</strong> with pygame.time.Clock()—easily overlooked but essential for consistent performance.</li></ul><p>🧠 <strong>Interesting AI-Generated Code Examples</strong></p><p>Full code can be found here : <a href="https://github.com/Dankhan11/space-invaders.git">https://github.com/Dankhan11/space-invaders.git</a></p><p>📸 <strong>Screenshots or Gameplay Footage</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*zjlKGz3TRyeXnWYKNy_rpA.png" /><figcaption>Initial development with a single prompt</figcaption></figure><p>Chance for user survival when the game starts was very minimal therefore changes had to be made in order to incorporate this. The way that the game operated however was quite good and matched the rules that I had set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*WuJ-hQBUuQQM0zNM3Ip00A.png" /><figcaption>Gameplay after changes had been made now incorporating multiple levels as well as varying difficulty and changes to the UI</figcaption></figure><h3>🧭 Final Reflections</h3><p>Building Space Invaders with Python, Pygame, and an AI assistant was more than just a fun coding challenge — it was a real shift in how I think about programming and learning. Instead of getting stuck on bugs or spending hours on documentation, I was able to ask targeted questions, get tailored answers, and <strong>focus on building</strong>. That feedback loop made development feel smoother and more creative.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164526801881" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data journey[0][1]]]></title>
            <link>https://medium.com/@khandanial114/becoming-a-data-scientist-0-1-7897dba2e8b0?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/7897dba2e8b0</guid>
            <category><![CDATA[my-coding-journey]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 14:01:00 GMT</pubDate>
            <atom:updated>2025-06-15T20:19:33.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-YRduMpl_OCvjWGz8EP8w.jpeg" /><figcaption>Data visualisation with some active recall</figcaption></figure><p>Continuing my journey into data science, I started by focusing on the more theoretical side understanding data and all things associated with it. In today’s data-driven world, understanding the foundational concepts of data is essential for anyone working with technology. Whether you’re diving into data science, software engineering, or analytics, grasping the intricacies of data objects, attributes, and quality can set you apart.</p><p>Poor data quality can have a very negative effect on how insights can be drawn from data. It is not uncommon for objects to be missing one or more values , in some cases the information was not collected ; whilst in other cases, some attributes are simply inapplicable to the data instances.</p><p><strong>Examples of poor data quality :</strong></p><ul><li>Noise</li><li>Outliers</li><li>Missing values</li><li>Duplicate dat</li></ul><h3>Data Objects and Attributes</h3><h3>What Are Data Objects?</h3><p>A data object represents an entity in the real world, often stored in a database as data tuples. Each object can have multiple characteristics, called attributes.</p><h3>Types of Attributes</h3><p><strong>Nominal Attributes</strong>:</p><ul><li>Represent categories or names.</li><li>Examples: Colours (red, green), Gender (male, female).</li><li>Mathematical operations are not applicable.</li></ul><p><strong>Binary Attributes</strong>:</p><ul><li>Have only two possible states: True/False or 0/1.</li></ul><p><strong>Ordinal Attributes</strong>:</p><ul><li>Represent ordered data but without measurable differences.</li><li>Examples: Rankings, Grades (A, B, C).</li></ul><p><strong>Numeric Attributes</strong>: Quantifiable and measurable characteristics</p><p><strong>Discrete Attributes</strong>: Finite values (e.g., number of children).</p><p><strong>Continuous Attributes</strong>: Infinite range of values (e.g., height, temperature).</p><h3>Characteristics of Data</h3><h4>Dimensionality</h4><p>The number of attributes in a dataset. High dimensionality can make analysis complex but also rich in insights.</p><h4>Sparsity</h4><p>Datasets with many zero or empty values are sparse.</p><ul><li><strong>Advantage</strong>: Sparse data only stores non-zero values, saving space and computation time.</li></ul><h4>Resolution</h4><ul><li><strong>High Resolution</strong>: May introduce noise and obscure patterns.</li><li><strong>Low Resolution</strong>: Risks oversimplifying data, potentially hiding important details.</li></ul><h3>Size</h3><p>Large datasets bring challenges like:</p><ol><li><strong>Too Much Data</strong>: Difficult to store or process.</li><li><strong>Continuous Data Streams</strong>: Require real-time (“online”) processing.</li></ol><h3>Data Representations</h3><h4>Basic Records</h4><ul><li><strong>Transaction Data</strong>: Represents records of item sets (e.g., products purchased).</li><li><strong>Data Matrix</strong>: Rows are objects, and columns are features.</li><li><strong>Sparse Matrix</strong>: Mostly zero or empty values.</li><li><strong>Document Data</strong>: Represents word-frequency relationships (e.g., document-term matrices).</li></ul><h4>Graphs</h4><p>Used to represent relationships between data objects (e.g., social networks).</p><h4>Ordered Data</h4><p>Includes sequences with a specific order, such as time-series data.</p><h3>Data Quality</h3><h4>Key Dimensions</h4><ol><li>Accessibility</li><li>Accuracy</li><li>Completeness</li><li>Consistency</li><li>Credibility</li><li>Relevance</li><li>Timeliness</li><li>Uniqueness</li><li>Validity</li></ol><h3>Common Problems</h3><ul><li><strong>Noise</strong>: Unwanted data or modified values.</li><li><strong>Outliers</strong>: Data points significantly different from the majority.</li><li><strong>Missing Values</strong>: Gaps in the dataset.</li><li><strong>Duplicate Data</strong>: Redundant or near-identical entries.</li><li><strong>Fake/Wrong Data</strong>: Incorrect or intentionally misleading data (e.g., fake news).</li></ul><h3>Similarity and Dissimilarity</h3><h3>Definitions</h3><ul><li><strong>Similarity</strong>: Numerical measure of how alike two objects are (range: 0 to 1).</li><li><strong>Dissimilarity</strong>: Numerical measure of difference (range: 0 to ∞).</li></ul><h3>Distance Measures</h3><ul><li><strong>Euclidean Distance</strong>: The geometric distance in multi-dimensional space.</li><li><strong>Minkowski Distance</strong>: Generalisation of Euclidean distance.</li></ul><h3>Transformations</h3><p>Data transformations convert similarity to dissimilarity (or vice versa) and scale values into specific ranges (e.g., 0 to 1). This ensures consistency and comparability across different datasets.</p><h3>Conclusion</h3><p>Understanding these data concepts is critical for analyzing and processing information effectively. By mastering these foundational ideas, you’ll be better equipped to tackle challenges in data science, engineering, or any data-centric field.</p><p>Tomorrow we will try implementing all of the things we have learnt so far</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7897dba2e8b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Journey[0][0]]]></title>
            <link>https://medium.com/@khandanial114/week-1-trying-to-become-a-data-scientist-92d07dd18010?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d07dd18010</guid>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 19:29:49 GMT</pubDate>
            <atom:updated>2025-06-16T11:16:46.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oxpb3qvrneafVF3Dx2V6TA.jpeg" /><figcaption>Reading : <a href="http://myweb.sabanciuniv.edu/rdehkharghani/files/2016/02/The-Morgan-Kaufmann-Series-in-Data-Management-Systems-Jiawei-Han-Micheline-Kamber-Jian-Pei-Data-Mining.-Concepts-and-Techniques-3rd-Edition-Morgan-Kaufmann-2011.pdf">J. Han, M. Kamber, J. Pei, “Data Mining: Concepts and Techniques”, 3rd edition, Elsevier/Morgan Kaufmann, 2012</a></figcaption></figure><p>Like any student who suddenly discovers their calling, I began my journey to becoming a data scientist by binge-watching an insane number of videos from successful individuals in the field. Their stories made me realise the importance of mastering the fundamentals, particularly in statistics, machine learning, and data mining. Here’s what I’ve learned so far:</p><h3>What is Data Mining?</h3><p>Data mining is the <strong>non-trivial extraction of implicit, previously unknown, and potentially useful information from data</strong>. Think of it as exploring and analysing large datasets, often with the help of automatic or semi-automatic tools, to uncover meaningful patterns and insights.</p><h3>What is Machine Learning?</h3><p>Tom Mitchell defines it as:<br><em>“A computer program is said to learn from experience (E) with respect to some tasks (T) and performance measure (P), if its performance at tasks in T, as measured by P, improves with experience E.”</em><br>In essence, it’s teaching computers to learn from data.</p><h3>Key Concepts in Data Science</h3><h3>Data and Datasets</h3><ul><li><strong>Data</strong>: Characteristics, either numerical or categorical, collected through observation.</li><li><strong>Dataset</strong>: A collection of items (records or observations) described by a set of features, such as the mass of an object or the timestamp of an event.</li></ul><h3>Knowledge Representation</h3><p>Knowledge can be represented in various ways:</p><ol><li><strong>Propositions</strong>: Simple statements or laws (e.g., “Smaller animals have a faster heartbeat”).</li><li><strong>Narratives</strong>: Descriptions or storytelling.</li><li><strong>Models</strong>: Mathematical or computational representations (e.g., formulas or algorithms).</li></ol><h3>What is a Model?</h3><p>A model is a simplified representation of reality, used to explain, predict, or understand phenomena. Models use:</p><ul><li><strong>Features</strong>: Independent variables (inputs).</li><li><strong>Responses</strong>: Dependent variables (outputs).</li></ul><h3>Types of Variables</h3><ol><li><strong>Numeric/Continuous</strong>: Real numbers (e.g., temperature, voltage).</li><li><strong>Categorical/Discrete</strong>: Categories without inherent order (e.g., gender).</li><li><strong>Ordinal</strong>: Categories with meaningful order (e.g., low/medium/high).</li></ol><h3>Attributes in Data Science</h3><ul><li><strong>Nominal</strong>: Names or labels (e.g., hair color).</li><li><strong>Binary</strong>: Only two states (e.g., yes/no).</li><li><strong>Ordinal</strong>: Ordered but with undefined distances (e.g., customer satisfaction levels).</li><li><strong>Numeric</strong>: Measurable quantities (e.g., weight, height).</li></ul><h3>Types of Machine Learning</h3><h3>Supervised Learning</h3><p>This involves learning a mapping function from inputs (X) to outputs (Y) so that predictions can be made for unseen data.<br><strong>Examples</strong>:</p><ul><li><strong>Classification</strong>: Assigning labels (e.g., spam or not spam).</li><li><strong>Regression</strong>: Predicting continuous values (e.g., house prices).</li></ul><h3>Unsupervised Learning</h3><p>Unsupervised learning works without labeled outputs and focuses on finding patterns in data.<br><strong>Examples</strong>:</p><ul><li><strong>Clustering</strong>: Grouping similar items (e.g., customer segmentation).</li><li><strong>Association Analysis</strong>: Discovering rules (e.g., market-basket analysis).</li><li><strong>Outlier Analysis</strong>: Identifying anomalies (e.g., fraud detection).</li></ul><h3>Challenges in Data Mining</h3><ol><li><strong>Methodology</strong>: Dealing with uncertain, noisy, or incomplete data.</li><li><strong>User Interaction</strong>: Enhancing user understanding and incorporating domain knowledge.</li><li><strong>Scalability</strong>: Extracting insights efficiently from massive datasets.</li><li><strong>Diversity</strong>: Handling dynamic, complex data types.</li><li><strong>Ethics</strong>: Privacy and societal implications of data mining.</li></ol><h3>Central Tendency and Dispersion</h3><h3>Mean:</h3><p>Averages can be skewed by outliers. To address this, we use methods like <strong>trimmed means</strong> (removing extreme values).</p><h3>Median:</h3><p>Finding the exact median for large datasets can be time-consuming. Using grouped data can provide an efficient estimate.</p><h3>Measuring Central Tendency and Dispersion</h3><p>In statistics, understanding the central tendency (mean, median, mode) is crucial. However, these metrics don’t tell the whole story about the spread or variability of data, which brings us to <strong>variance</strong> and <strong>standard deviation (SD).</strong></p><h3>What is Variance?</h3><p>Variance measures the average squared difference between each data point and the mean. It tells us how far data points are spread out in a dataset. A higher variance means the data is more spread out, while a lower variance indicates the data is closer to the mean.</p><h3>What is Standard Deviation?</h3><p>Standard deviation (SD) is simply the square root of variance. It provides a measure of spread in the same units as the data, making it more interpretable.</p><h3>Why Are Variance and SD Important?</h3><p>These metrics help us understand how consistent or volatile our data is:</p><ul><li>A small SD indicates that data points are close to the mean (e.g., test scores of students in a class where everyone performed similarly).</li><li>A large SD signals more variability (e.g., incomes in a population where some individuals earn significantly more than others).</li></ul><p>In machine learning, SD and variance play key roles in understanding the data distribution and designing robust models. For instance:</p><ul><li>Models with <strong>high variance</strong> may overfit the data.</li><li><strong>Regularisation techniques</strong> often aim to reduce variance to improve generalisation.</li></ul><h3>Next Steps</h3><p>This week has been a deep dive into the foundational concepts of data science. Next, I’ll focus on hands-on projects, learning Python libraries like NumPy and Pandas, and exploring real-world datasets.</p><p>If you’re on a similar journey, remember: start with the basics, stay curious, and don’t be afraid to dive into the complexities. Data science is as much about persistence as it is about knowledge.</p><p>Stay tuned for Week 2!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d07dd18010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Bases: History, ER Modelling]]></title>
            <link>https://medium.com/@khandanial114/data-bases-history-er-modelling-244020f70e38?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/244020f70e38</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[entity-relationship-model]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 15:19:29 GMT</pubDate>
            <atom:updated>2024-01-05T15:19:29.737Z</atom:updated>
            <content:encoded><![CDATA[<p>This is general info for the database management course , containing information about ER modelling and database history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*GE3xHwIX2GiIVocdHAOfcg.png" /></figure><p>The models above were procedural in nature, to get data you need to write a program which will say how to access the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*gtGR73NqlY2ylhfn_I-1Cg.png" /></figure><p>Whereas the relational model is declarative — for example the programming language prologue is declarative</p><p><strong><em>Simple definitions:</em></strong></p><p>Entities: An entity is an object about with physical or conceptual existence</p><p>Entity type: structural specification of entity and associated attributes</p><p>Entity set: collection of all entities for a particular entity type</p><p>Attributes: Properties which describe the entities</p><p>Composite attributes: Attributes which can be divided into smaller sub parts</p><p>ACID:</p><ul><li>Atomicity: transactions must be fully completed or not done at all</li><li>Consistency : each transaction changes from one consistent state to another</li><li>Isolation: Concurrent transactions are processed sequentially [any order will lead to the same execution]</li><li>Durability: Once a transaction is committed, the event will persist even in the event of a system failure.</li></ul><p>DB Design Process:</p><ul><li>Requirements collection and analysis</li><li>Conceptual design</li><li>Logical design / Data model mapping</li><li>Physical design</li></ul><p>Stored vs Derived Attributes:</p><ul><li>Derived attributes value is calculated by using the value of another stored attribute such as age which can be derived from year of birth</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=244020f70e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search Tree — Explained]]></title>
            <link>https://medium.com/@khandanial114/binary-search-tree-explained-cd8014ce0ca4?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd8014ce0ca4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 14:10:31 GMT</pubDate>
            <atom:updated>2024-01-05T14:10:31.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search Tree — Explained</h3><p>One of the key data structures which I have started to learn and implement are trees specifically Binary Search Trees.</p><p>A binary search tree is arranged in such a way that values which are smaller are put on the left whilst values which are greater are put on the right hand side. As shown in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*xrSLy6ft46qAMB_BdVbVlA.png" /><figcaption>BST</figcaption></figure><p>This becomes useful whenever you are searching for elements as you can simply traverse through the tree easily as it follows a set of conditions.</p><p>One of the key things to consider is the maximum number of searches taken to find a specific element. The maximum number depends upon the height of the tree. In this case the height of the tree is 3 therefore the maximum search number is also 3.</p><p><strong><em>Problems with Binary Search Tree: [Depends how key elements are inserted ]</em></strong></p><p>Key1 : 30,40,10,50,5,20,5,35</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*xrSLy6ft46qAMB_BdVbVlA.png" /><figcaption>Tree for the key1 above</figcaption></figure><p>Key2: 50,45,35,30,20,10,5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Pvm-QqC9sP8GCDApiPhbNw.png" /><figcaption>Binary Search Tree for Key2 O(n) time complexity</figcaption></figure><p>The main problem which can be seen above is when the root node is the greatest the height of the tree increases significantly as each element after it is smaller. Meaning it will always branch off to the left. Increasing the maximum number of searches it takes to find an element.</p><p>Balanced Trees and efficiency:</p><p>We can call a tree balanced if for each node in the tree, the heights of its left and right subtree do not differ by more than 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*5MgONmEbClg29J0q3S1lrA.png" /></figure><p>b = height(left-subtree) — height(right-subtree)</p><p>In a binary search tree (BST), rotations are operations that maintain the BST property by reorganising nodes when necessary. There are two main types of rotations: left rotations and right rotations. The decision on which rotation to perform depends on the specific situation and violation of the BST property.</p><p>Left Rotation (Right-Right Case):</p><ul><li>Triggered when the right subtree of the right child of a node becomes unbalanced.</li><li>To fix it, you perform a left rotation on the unbalanced node.</li></ul><p>Example:</p><pre>   A<br>    \<br>     B<br>      \<br>       C</pre><p>After left rotation:</p><pre>     B<br>    / \<br>   A   C</pre><p>Right Rotation (Left-Left Case):</p><ul><li>Triggered when the left subtree of the left child of a node becomes unbalanced.</li><li>To fix it, you perform a right rotation on the unbalanced node.</li></ul><p>Example:</p><pre>       C<br>      /<br>     B<br>    /<br>   A</pre><p>After Right Rotation:</p><pre>     B<br>    / \<br>   A   C</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd8014ce0ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selection sort vs Insertion sort : Python implementation]]></title>
            <link>https://medium.com/@khandanial114/selection-sort-vs-insertion-sort-python-implementation-c855ead05b62?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/c855ead05b62</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 11:56:01 GMT</pubDate>
            <atom:updated>2023-10-14T11:56:01.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Selection sort vs Insertion sort : Python implementation</h3><h3><strong>Selection Sort:</strong></h3><p>To sort the array A:</p><ul><li>Go through all its elements, find the smallest one, and put it in first position</li><li>Go through all its remaining elements, find the smallest one, and put it in second position</li><li>Repeat the steps until A is sorted</li></ul><p>Selection sort — python</p><pre><br>#find the smallest/minimum number and return the index of that number<br>def findMin(i,A):<br>    imin = i<br>    for j in range(i+1,len(A)):<br>        if A[j] &lt; A[imin]:<br>            imin = j<br>    return imin<br>        <br>#swap variables at one index with a variable from another index using temp variable<br>def swap(i,j,A):<br>    temp = A[i]<br>    A[i] = A[j]<br>    A[j] = temp<br>    <br>    return A<br><br><br>def selectionSort(A):<br>     for i in range(len(A)):<br>        #find min element of A[i]<br>        imin = findMin(i,A)<br>        #Swap element with position i <br>        swap(i,imin,A)<br>        <br><br>##test the code <br><br>#test = [1,3,16,242,4,2,1,35,2523554,6,34353,3,19]<br>#selectionSort(test)<br>#print(test)<br>     <br>## should print [1, 1, 2, 3, 3, 4, 6, 16, 19, 35, 242, 34353, 2523554]<br>        <br>      <br></pre><h3>Insertion sort</h3><p>Steps:</p><p>To sort array A:</p><ul><li>Pick A[1] and insert it before/after A[0]</li><li>Pick A[2] and insert it in the correct position in A[0],A[1]</li><li>Pick A[3] and insert it in its right position in A[0], A[1], A[2]</li><li>Continue and repeat the steps</li></ul><p>At each step we pick an element of A[i] of A and insert in its place in the part of the array which is already sorted A[0 ….. i-1]</p><pre>def insertionSort(A):<br>      for i in range(1, len(A)):<br>        print(A)<br>        #function called insert taking the value we want to insert the array and the index where the insertion will take place <br>        insert(A[i], A, i)<br>        time.sleep(2)<br><br><br>def insert(v, A, hi):<br>    #insert the value v in a[0..hi-1]  (sorted)<br>    for i in range(h1-1,-1,-1):<br>        if v &lt; A[i]:<br>          A[i + 1] = A[i]<br>        else:<br>          A[i+1] = v<br>          return<br>    A[0] = v<br>           <br>          <br><br>#######tests <br>   <br>A = [1,2,23,4,3,543,64565,467,657,65,757,34,52,3123,5,46,2,7,8,0]<br>insertionSort(A)<br>print(A)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c855ead05b62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures and Algorithms: Searching in python — Arrays]]></title>
            <link>https://medium.com/@khandanial114/data-structures-and-algorithms-searching-in-python-arrays-ebcc2048d48a?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebcc2048d48a</guid>
            <category><![CDATA[searching-algorithm]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linear-search]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 14:00:12 GMT</pubDate>
            <atom:updated>2023-10-05T14:00:12.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Structures and Algorithms: Searching in python — Arrays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*P82lcUdNpJG6Aq-yIk7j9w.jpeg" /></figure><p>Introduction: Searching for a specific value within an array is a fundamental operation in computer science and programming. To accomplish this task effectively, one must consider various algorithms, each with its own set of strengths and weaknesses. In this article, we will delve into the world of searching algorithms for arrays in Python, exploring their intricacies, and examining critical factors like time and space complexity.</p><p>Understanding the Basics: Before we dive into the specific searching algorithms, let’s clarify some essential concepts:</p><p><em>Definitions</em></p><p><strong>Space Complexity</strong>: Space complexity refers to the total amount of memory space used by an algorithm, encompassing both the memory required for the algorithm’s execution and the space used to store input values during execution. Understanding space complexity is crucial for optimising memory usage in your programs.</p><p><strong>Time Complexity</strong>: Time complexity measures the time it takes for an algorithm to execute. It helps us evaluate the efficiency of an algorithm and is a key consideration when choosing the right search algorithm for a particular problem.</p><p><strong><em>Exploring Searching Algorithms:</em></strong></p><p>Linear Search: The simplest searching algorithm, linear search, involves traversing an array element by element to find a specific value. Here’s a Python implementation:</p><pre>def linear_search(arr, target):<br>    for i in range(len(arr)):<br>        if arr[i] == target:<br>            return True<br>    return False</pre><p>Linear search is easy to understand and implement, but its time complexity is O(n), where n is the size of the array. This means that as the size of the array increases, the time taken to find a value grows linearly. It’s ideal for small datasets or when the elements are not in any particular order.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebcc2048d48a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuples in python]]></title>
            <link>https://medium.com/@khandanial114/tuples-in-python-fd4f72ef9c2c?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4f72ef9c2c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tuples-in-python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sat, 27 May 2023 20:44:58 GMT</pubDate>
            <atom:updated>2023-05-27T20:44:58.293Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python, a tuple is an ordered, immutable collection of elements enclosed in parentheses (). Tuples are similar to lists but have the key difference that they cannot be modified once created. This immutability makes tuples useful for representing fixed collections of values.</p><p>Here’s an example to illustrate tuples in Python:</p><pre># Creating a tuple<br>my_tuple = (1, 2, 3, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;)</pre><pre># Accessing elements in a tuple<br>print(my_tuple[0])    # Output: 1<br>print(my_tuple[3])    # Output: &#39;a&#39;</pre><pre># Tuple slicing<br>print(my_tuple[1:4])  # Output: (2, 3, &#39;a&#39;)</pre><pre># Length of a tuple<br>print(len(my_tuple))  # Output: 6</pre><pre># Iterating over a tuple<br>for item in my_tuple:<br>    print(item)</pre><pre># Trying to modify a tuple (results in an error)<br>my_tuple[0] = 10      # TypeError: &#39;tuple&#39; object does not support item assignment</pre><p>In the example above, we first create a tuple my_tuple containing integers and strings. We access elements of the tuple using indexing, where the first element has an index of 0. Tuple slicing allows us to extract a portion of the tuple. The len() function returns the length of the tuple.</p><p>Tuples can also be used in iteration, just like lists. In the example, we iterate over the elements of my_tuple using a for loop.</p><p>Finally, when attempting to modify a tuple, such as assigning a new value to an element, an error will occur because tuples are immutable. This immutability guarantees that the elements of a tuple cannot be changed after creation.</p><p>Remember that parentheses are not always required to define a tuple in Python. For example, you can create a tuple without parentheses:</p><pre>my_tuple = 1, 2, 3, 4</pre><p>This is known as tuple packing. However, using parentheses can enhance code readability, especially in cases where the tuple contains complex or mixed data type</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4f72ef9c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[List comprehensions in Java and Python]]></title>
            <link>https://medium.com/@khandanial114/list-comprehensions-in-java-and-python-2028509a640b?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/2028509a640b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sun, 14 May 2023 11:22:07 GMT</pubDate>
            <atom:updated>2023-05-14T11:22:07.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*3PHZW300-xYJZxtnptr7CQ.png" /></figure><p>I’ve been trying to start doing some hackerrank recently to get ready for interviews and imporve my skillset. One of the topics that came up was list comprehensions so I thought I would share some info on what I’ve learnt.</p><p>List comprehensions are a concise way to create lists in Python and Java. They allow you to generate a new list by iterating over an existing iterable object (such as a list, tuple, or range) and applying an expression or condition. The resulting list comprehension code is typically shorter and more readable than traditional loops.</p><p>Let’s start with Python:</p><h3>Python List Comprehensions:</h3><p>In Python, the syntax for list comprehensions is as follows:</p><pre>new_list = [expression for item in iterable if condition]</pre><p>Here’s a breakdown of each component:</p><ul><li>new_list: The resulting list generated by the list comprehension.</li><li>expression: The expression or transformation to be applied to each item in the iterable.</li><li>item: The variable that represents each item in the iterable.</li><li>iterable: The existing iterable object, such as a list or range.</li><li>if condition (optional): A condition that filters which items are included in the resulting list.</li></ul><p>Example 1: Squaring numbers in a list</p><pre>numbers = [1, 2, 3, 4, 5]<br>squared = [num ** 2 for num in numbers]<br>print(squared)  # Output: [1, 4, 9, 16, 25]</pre><p>Example 2: Filtering even numbers</p><pre>numbers = [1, 2, 3, 4, 5]<br>even_numbers = [num for num in numbers if num % 2 == 0]<br>print(even_numbers)  # Output: [2, 4]</pre><p>Now let’s move on to Java:</p><h3>Java List Comprehensions:</h3><p>Java doesn’t have built-in list comprehensions like Python, but you can achieve similar functionality using loops and lambda expressions.</p><p>Example 1: Squaring numbers in a list</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);<br>        List&lt;Integer&gt; squared = new ArrayList&lt;&gt;();</pre><pre>        for (int num : numbers) {<br>            squared.add(num * num);<br>        }</pre><pre>        System.out.println(squared);  // Output: [1, 4, 9, 16, 25]<br>    }<br>}</pre><p>Example 2: Filtering even numbers</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);<br>        List&lt;Integer&gt; evenNumbers = new ArrayList&lt;&gt;();</pre><pre>        for (int num : numbers) {<br>            if (num % 2 == 0) {<br>                evenNumbers.add(num);<br>            }<br>        }</pre><pre>        System.out.println(evenNumbers);  // Output: [2, 4]<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2028509a640b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphism in Java]]></title>
            <link>https://medium.com/@khandanial114/polymorphism-in-java-33d63c9a89e7?source=rss-83070a447005------2</link>
            <guid isPermaLink="false">https://medium.com/p/33d63c9a89e7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Danial Khan]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 16:40:06 GMT</pubDate>
            <atom:updated>2023-04-02T16:40:06.043Z</atom:updated>
            <content:encoded><![CDATA[<p>Polymorphism is the ability of an object to take on many forms. In Java, polymorphism allows objects of different classes to be treated as if they were objects of the same class. This is achieved through inheritance and interfaces, which allow classes to share common methods and properties.</p><p>Here are some examples of polymorphism in Java:</p><ol><li><strong>Method Overloading:</strong></li></ol><p>Method overloading is a form of polymorphism where a single method can have multiple signatures, each with a different set of parameters. Here’s an example of method overloading:</p><pre>public class Calculator {<br>    public int add(int a, int b) {<br>        return a + b;<br>    }</pre><pre>    public double add(double a, double b) {<br>        return a + b;<br>    }<br>}</pre><p>In this example, the Calculator class has two add methods with different parameter types. The first add method takes two integers and returns an integer, while the second add method takes two doubles and returns a double. Both methods have the same name, but they have different parameter types, allowing them to be called with different types of arguments.</p><p>Here’s an example of calling the add methods:</p><pre>Calculator calculator = new Calculator();<br>int sum1 = calculator.add(1, 2);<br>double sum2 = calculator.add(3.14, 2.71);</pre><p>In this example, a Calculator object is created and the add methods are called with different types of arguments. The first add method returns an integer, while the second add method returns a double.</p><ol><li><strong>Method Overriding:</strong></li></ol><p>Method overriding is a form of polymorphism where a subclass can provide a different implementation of a method that is already defined in its superclass. Here’s an example of method overriding:</p><pre>public class Animal {<br>    public void speak() {<br>        System.out.println(&quot;Animal speaks&quot;);<br>    }<br>}</pre><pre>public class Dog extends Animal {<br>    @Override<br>    public void speak() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>In this example, the Animal class has a speak method that prints &quot;Animal speaks&quot; to the console. The Dog class extends the Animal class and overrides the speak method with its own implementation that prints &quot;Dog barks&quot; to the console.</p><p>Here’s an example of calling the speak method:</p><pre>Animal animal = new Animal();<br>animal.speak();</pre><pre>Dog dog = new Dog();<br>dog.speak();</pre><pre>Animal animal2 = new Dog();<br>animal2.speak();</pre><p>In this example, an Animal object is created and its speak method is called, which prints &quot;Animal speaks&quot; to the console. A Dog object is created and its speak method is called, which prints &quot;Dog barks&quot; to the console. An Animal object is created and assigned a Dog object, and its speak method is called, which also prints &quot;Dog barks&quot; to the console. This demonstrates how a subclass can provide a different implementation of a method that is already defined in its superclass.</p><ol><li><strong>Interfaces:</strong></li></ol><p>Interfaces are a way to achieve polymorphism in Java by defining a set of methods that classes can implement. Here’s an example of using an interface:</p><pre>public interface Shape {<br>    double getArea();<br>}</pre><pre>public class Square implements Shape {<br>    private double side;</pre><pre>    public Square(double side) {<br>        this.side = side;<br>    }</pre><pre>    @Override<br>    public double getArea() {<br>        return side * side;<br>    }<br>}</pre><pre>public class Circle implements Shape {<br>    private double radius;</pre><pre>    public Circle(double radius) {<br>        this.radius = radius;<br>    }</pre><pre>    @Override<br>    public double getArea() {<br>        return Math.PI * radius * radius;<br>    }<br>}</pre><p>In this example, the Shape interface defines a getArea method that returns a double. The Square class and Circle class both implement the Shape interface and provide their own implementation of the getArea method.</p><p>Here’s an example of calling the getArea method:</p><pre>Square square = new Square(5);<br>double squareArea = square.getArea();</pre><pre>Circle circle = new Circle(2.5);<br>double circleArea = circle.getArea();</pre><p>In this example, a Square object is created with a side length of 5, and its getArea method is called, which returns 25. A Circle object is created with a radius of 2.5, and its getArea method is called, which returns approximately 19.63. Both objects implement the Shape interface and provide their own implementation of the getArea method, demonstrating how interfaces can be used to achieve polymorphism in Java.</p><p>Polymorphism is a powerful feature of Java that allows for flexible and modular code. By using inheritance and interfaces, classes can share common methods and properties, and objects of different classes can be treated as if they were objects of the same class. This allows for greater flexibility and modularity in the code, and can make it easier to maintain and extend the code in the future.</p><p>Upcasting and downcasting are two ways to manipulate object references in Java that are related to polymorphism.</p><p>Upcasting is when an object of a subclass is assigned to a variable of its superclass. This is safe to do because the subclass object contains all of the properties and methods of its superclass. Here’s an example of upcasting:</p><pre>public class Animal {<br>    public void speak() {<br>        System.out.println(&quot;Animal speaks&quot;);<br>    }<br>}</pre><pre>public class Dog extends Animal {<br>    @Override<br>    public void speak() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><pre>public class UpcastExample {<br>    public static void main(String[] args) {<br>        Dog dog = new Dog();<br>        Animal animal = dog;</pre><pre>        animal.speak(); // prints &quot;Dog barks&quot;<br>    }<br>}</pre><p>In this example, a Dog object is created and assigned to a variable of type Animal using upcasting. The speak method is called on the Animal variable, which prints &quot;Dog barks&quot; to the console. This demonstrates how upcasting can be used to manipulate object references in Java.</p><p>Downcasting is when an object of a superclass is assigned to a variable of its subclass. This is not always safe to do, because the superclass object may not contain all of the properties and methods of its subclass. Here’s an example of downcasting:</p><pre>public class Animal {<br>    public void speak() {<br>        System.out.println(&quot;Animal speaks&quot;);<br>    }<br>}</pre><pre>public class Dog extends Animal {<br>    public void bark() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><pre>public class DowncastExample {<br>    public static void main(String[] args) {<br>        Animal animal = new Dog();<br>        Dog dog = (Dog) animal;</pre><pre>        dog.bark(); // prints &quot;Dog barks&quot;<br>    }<br>}</pre><p>In this example, an Animal object is created and assigned to a variable of type Animal. The Animal object is then downcast to a Dog object using a cast operator. The bark method is called on the Dog variable, which prints &quot;Dog barks&quot; to the console. This demonstrates how downcasting can be used to manipulate object references in Java.</p><p>It’s important to note that downcasting can cause a ClassCastException if the object being downcast is not actually an instance of the subclass being downcast to. To avoid this, it&#39;s recommended to use the instanceof operator to check the type of the object before downcasting it.</p><p>Overall, upcasting and downcasting are useful techniques for manipulating object references in Java that are related to polymorphism. Upcasting can be used to assign a subclass object to a variable of its superclass, while downcasting can be used to assign a superclass object to a variable of its subclass. Both techniques can be used to create flexible and modular code that takes advantage of Java’s polymorphism features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33d63c9a89e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>