<?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 Faruqraji on Medium]]></title>
        <description><![CDATA[Stories by Faruqraji on Medium]]></description>
        <link>https://medium.com/@faruqraji604?source=rss-deb25eb8df4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rt3A8intz1GJmM7-</url>
            <title>Stories by Faruqraji on Medium</title>
            <link>https://medium.com/@faruqraji604?source=rss-deb25eb8df4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:25:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faruqraji604/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 Owambe Weddi­­­ng Greetings to O(1) Lookups: How We Conquered Data Structures, Algorithms…]]></title>
            <link>https://medium.com/@faruqraji604/from-owambe-weddi-ng-greetings-to-o-1-lookups-how-we-conquered-data-structures-algorithms-c5d4e6c3b57b?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5d4e6c3b57b</guid>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 09:09:13 GMT</pubDate>
            <atom:updated>2026-11-28T09:09:13.828Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>­­­From Owambe Weddi­­­ng Greetings to O(1) Lookups: How We Conquered Data Structures, Algorithms, and SQL Without Shedding Tears!</strong></h3><p><em>A beginner survival guide for anyone who used to run away from DSA and Big-O notation. Grab your chin-chin and cold Zobo, let us break it down together!</em></p><p>DataraFlow Week 11–12</p><p><strong>1. My People, Make We Settle Down: The DSA Panic is Over!</strong></p><p>Let us be honest with ourselves for a moment. You know that quiet, trembling panic that hits your chest whenever someone in tech mentions ‘Data Structures and Algorithms’ or ‘Big-O notation’? Ehen! That cold sweat where your heart starts doing rapid legwork, as if you owe the entire neighborhood money? That was exactly me and many of us when Week 11 of our data fellowship kicked off!</p><p>For a very long time, society made us believe that Data Structures and Algorithms (DSA) was an exclusive club reserved for mathematicians with three PhDs or people who dream in binary code. Whenever we opened those classic textbook tutorials, we saw scary Greek symbols, complicated math equations, and intimidating diagrams that looked like ancient Egyptian hieroglyphics. Before you knew it, we would gently close our laptops, say ‘God forbid’, and go and fry plantain. <em>LOL, E GO DO BE THAT!!!</em></p><p>But you see this week? We had a massive breakthrough, and I want us to celebrate it together! We discovered that Data Structures and Algorithms are not witchcraft at all. In fact, no be juju(magic), na everyday common sense! DSA is simply about saving our computer from unnecessary suffering, the exact same way we make smart decisions every single day in our homes, at market squares, and at family parties.</p><p>In this post, we are going to walk side-by-side through our entire journey: how we decoded Big-O using relatable Nigerian life, how we solved all 10 algorithmic puzzles step-by-step with zero fluff, how our code smashed all speed benchmarks in under 11 milliseconds, and how we took those exact same algorithmic superpowers straight into our SQL database. Come along with me, I promise you will laugh, learn, and never fear DSA again.</p><p><strong>2. Big-O Notation: The Nigerian Owambe Wedding Guide</strong></p><p>Before we write a single line of Python code, we must settle our score with the famous boss of computer science: Big-O notation. What is Big-O really? Strip away all the academic grammar, and Big-O is simply asking one practical question: As the amount of work grows bigger, how much more sweat will our computer suffer to finish it?</p><p>To make this super crystal clear and easy to digest, let us imagine ourselves attending a colorful, bustling Nigerian Owambe wedding reception on a Saturday afternoon.</p><p><strong>O(1) — Constant Time: Spotting the Couple on the High Table</strong></p><p>Imagine we step into a wedding marquee with 500 guests sitting under canopies. If someone asks us: ‘Where are the bride and groom?’, do we need to walk around and inspect every single chair in the hall? Never! All we do is look directly at the glittering High Table on the stage, gbem! We see them immediately. Whether only 50 guests show up or a massive crowd of 5,000 people storms the reception, it takes us the exact same 1 second to spot the couple. That is O(1) Constant Time. Zero extra sweat, regardless of crowd size!</p><p><strong>O(N) — Linear Time: Mum’s Famous ‘Go and Greet Everybody’ Command</strong></p><p>Now, contrast that with another very familiar scenario. Say I arrive at a Nigerian wedding reception with 200 guests, and my Nigerian mum tells me: ‘Go and greet everybody one by one’, funny that’s Nigerian mum for us! If there are 200 people, I greet 200 times. If 500 people come, I greet 500 times. If 1,000 guests arrive, my poor knees must bend down and greet 1,000 times! The work grows directly with the crowd.</p><p>That is O(N) Linear Time! If the crowd doubles, our knee bending doubles. If the input size N triples, our computer’s work triples proportionally. Fair and manageable, but the stress increases steadily.</p><p><strong>O(N²) — Quadratic Time: The Handshake Nightmare (Avoid Like Lagos Traffic!)</strong></p><p>Now, imagine the ultimate nightmare. Imagine my mum says: ‘Faruq, not only will you greet every guest, but for every single person you greet, you must introduce them to every other person sitting in the hall!’ Jesus is Lord! 200 guests greeting 200 other guests? That is 200 × 200 = 40,000 handshakes! If 500 guests attend, that becomes 250,000 handshakes! By the time we finish, the wedding reception is over, the caterer has packed the jollof rice coolers, the MC has gone home, and our knees have retired from service! That is O(N²) Quadratic Time, the terrible result of nested loops. We must avoid it like the third mainland bridge at 6:00 PM on a rainy Monday!</p><p><strong>O(log N) — Logarithmic Time: The Balogun Market Shoe Bargaining</strong></p><p>Have you ever bargained for shoes in Balogun market? The trader calls out: ‘N50,000!’ You immediately smile and counter with: ‘N10,000!’ He says: ‘Bring N35,000!’ You say: ‘Let us meet in the middle at N22,000!’ At every single offer, we cut the gap directly in half! Instead of counting every single naira one by one from 10,000 to 50,000, we zero in on the final price in just four or five quick splits! That is O(log N) Logarithmic Time. It is the secret power behind Binary Search.</p><p><strong>THE OWAMBE RULE OF COMPUTATION<br> </strong><em>Always remember: O(1) is instant like looking at the High Table; O(log N) cuts the crowd in half repeatedly; O(N) is greeting guests one by one; and O(N²) is greeting everyone and introducing them to everyone else! Whenever we write code, our mission is to pull our solutions away from O(N²) and bring them down to O(N) or O(log N)!</em></p><p><strong>3. The Toolbelt: Meet Our Everyday Data Structures</strong></p><p>Just like a master craftsman has specific tools in their box, we as data professionals have data structures. Each one has a specific personality and strength:</p><p>· <strong>1. Arrays &amp; Lists: </strong>Numbered chairs under the canopy! If you give me index 4, I jump straight to chair 4 in O(1) time. But if you tell me to look for Uncle Segun among 1,000 unlabelled chairs, I must inspect chair by chair in O(N) time.</p><p>· <strong>2. Hash Maps (Dictionaries): </strong>Mama Put having your name and your exact favorite order memorized! The moment you show up, she serves you your hot plate immediately in O(1) time. In Python, this is our dictionary, and it is our #1 weapon against sluggish code.</p><p>· <strong>3. Sets: </strong>The eagle-eyed bouncer at the wedding gate holding the exclusive VIP list. He ensures no duplicate gatecrashers enter, and checks whether your name is on the list in O(1) blink-of-an-eye speed.</p><p>· <strong>4. Linked Lists: </strong>A line of fuel kegs tied together with rope! Each keg knows only who is in front of it. Inserting a new keg in the middle is effortless, but jumping to the 10th keg means walking the rope link by link.</p><p>· <strong>5. Stacks: </strong>The pile of hot plates in Mama Put’s kitchen! Last plate placed on top is the First plate picked up (LIFO). Perfect for undo operations and validating nested brackets.</p><p>· <strong>6. Deques: </strong>The double-ended Danfo bus where passengers can politely board and alight from both the front and back doors in O(1) time without anyone climbing over seats.</p><p><strong>4. Step-by-Step Walkthrough: Conquering the 10 Algorithmic Tasks</strong></p><p>Now, let us get our hands dirty with the actual code! For our week 11 take-home project, we were handed 10 algorithmic problems covering the full spectrum of data structures. We structured every single solution inside our Jupyter Notebook with three clear parts: what the task asked, our first-person commentary on why we wrote the code, and an explanation of the underlying mechanics.</p><p><strong>Problem 1 (p01): Best K-Day Sales — The Jumia Sliding Window (max_window_sum)</strong></p><p>The Challenge: Imagine you manage an e-commerce store like Jumia or Konga. Given daily revenue numbers and an integer k, find the maximum sales revenue earned across any consecutive k days in O(N) time.</p><p>How We Solved It: A naive coder would recalculate the sum of all k days from scratch every single morning, that is O(N · k) sweat! Instead, we used a Sliding Window. We sum the first k days. Then, as our window slides forward each day, we subtract the day that just slipped out of the back, and add the new day coming in through the front! Window updates happen in O(1) time, completing the entire year in a single O(N) pass!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1RmRY9vSiSBDNIdWCpXIJQ.png" /></figure><figure><img alt="VS Code screenshot showing problem prompt, Python code for max_window_sum, and output confirming All 7 tests passed." src="https://cdn-images-1.medium.com/max/975/1*YlTNu6WEIP0P3lhtORPVhw.png" /><figcaption><em>Figure 1: Executing max_window_sum inside VS Code with O(N) sliding window and verifying all 7 unit tests pass.</em></figcaption></figure><p><strong>Problem 2 (p02): Pair with Sum K — The Danfo Conductor Two Pointers (pair_with_sum)</strong></p><p>The Challenge: Given an already sorted array of integers and a target sum, find two indices whose values sum up to the target in O(N) time and strictly O(1) auxiliary space (no extra dictionaries allowed!).</p><p>How We Solved It: Because the list is pre-sorted, we deployed two pointers! Imagine two bus conductors: one at the front seat (smallest value, left = 0) and one at the back seat (largest value, right = len — 1). We sum their values. If the sum is too small, the front conductor steps forward. If the sum is too large, the back conductor steps backward. They meet in the middle without allocating a single byte of extra memory. Our code was so fast it crushed the speed benchmark in just 3.4 milliseconds (limit was 50 ms), earning us a speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1iZLmRhiO2VIoSHO9lH8Gw.png" /></figure><figure><img alt="VS Code editor showing pair_with_sum code with output indicating All 7 tests passed and speed test passed in 3.4 ms with +1 bonus point." src="https://cdn-images-1.medium.com/max/975/1*nd1kcFBOVBB34ZAM7J58mg.png" /><figcaption><em>Figure 2: Verifying pair_with_sum in VS Code with two pointers, passing all 7 tests and smashing the speed bonus in 3.4 ms.</em></figcaption></figure><p><strong>Problem 3 (p03): Group Anagrams — Sorting Ingredients into Buckets (group_anagrams)</strong></p><p>The Challenge: Given a list of words, group words that are anagrams of each other together into clusters (e.g. ‘listen’ and ‘silent’ have the exact same letters).</p><p>How We Solved It: Think of preparing jollof rice. Whether you chop onions first or tomatoes first, the raw ingredients in the pot are identical! For each word, we sort its letters alphabetically and convert them into a tuple, like tuple(sorted(‘silent’)) -&gt; (‘e’, ‘i’, ‘l’, ’n’, ‘s’, ‘t’). We use this sorted tuple as the universal key in a dictionary, appending every matching word to that key’s bucket. Grouping happens in O(N · L log L) time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*LvhLOV7JIjWkgKhcI_8INg.png" /></figure><figure><img alt="VS Code screenshot demonstrating group_anagrams passing all 7 test cases cleanly." src="https://cdn-images-1.medium.com/max/975/1*6C1Xx6HumruPyXYa7g9s-A.png" /><figcaption><em>Figure 3: Grouping words into anagram clusters using character tuple dictionary hashing in VS Code.</em></figcaption></figure><p>The Challenge: Given an unsorted array of numbers, find the length of the longest streak of consecutive numbers (e.g. [100, 4, 200, 1, 3, 2] contains [1, 2, 3, 4], length 4). You must do it in O(N) average time, meaning you are strictly forbidden from sorting the array.</p><p>How We Solved It: We dumped all numbers into a Python set for O(1) instant lookups. Now, here is the genius move: How do we know if a number is the true leader of a streak? If num — 1 is NOT in the set! If num — 1 exists, we ignore it, because it is part of a streak that started earlier. But if num — 1 is absent, this number is the captain! We then count upwards (num + 1, num + 2…) until the streak breaks. This guarantees each number is touched at most twice. Our solution was so blazing fast it finished in 10.6 milliseconds, earning our second speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Sz08O-MDdAhks8Khx_cl9Q.png" /></figure><figure><img alt="VS Code editor showing longest_consecutive code and output confirming 7/7 tests passed with speed test passed in 10.6 ms (+1 bonus point)." src="https://cdn-images-1.medium.com/max/975/1*p2r9ERCfcHlXFKHtdRP8bQ.png" /><figcaption><em>Figure 4: Hash set streak search in VS Code finding longest consecutive runs in O(N) time and earning speed bonus in 10.6 ms.</em></figcaption></figure><p><strong>Problem 5 (p05): Reverse a Linked List — Flipping the Queue In-Place (reverse_list)</strong></p><p>The Challenge: Given the head of a singly linked list, reverse the list in-place so that the last node becomes the head, using O(1) auxiliary space.</p><p>How We Solved It: Imagine a line of people holding hands, facing right. To reverse them, we walk down the line using three pointers: prev, curr, and next_node. At every step, we save the next person in line, turn curr.next backward to point to prev, move prev forward to curr, and advance curr to next_node. By the time curr reaches None, prev is holding the new head of the reversed list! Zero new nodes created, pure O(N) time and O(1) space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*MR8HFQEm0ffWJzPrAxi9Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cbaFwpaDAqxzt_JLB-pazw.png" /><figcaption><em>Figure 5: Reversing singly linked list nodes in-place using pointer rewiring in VS Code.</em></figcaption></figure><p><strong>Problem 6 (p06): Balanced Parentheses — Mama Put’s Nested Bowls (is_balanced)</strong></p><p>The Challenge: Given a string containing brackets, parentheses, and braces (‘()’, ‘[]’, ‘{}’), determine if all opening brackets are closed in the correct nested order.</p><p>How We Solved It: Think of Mama Put nesting her plastic bowls. The last bowl you place inside must be the first bowl you remove! We used a Stack (LIFO). Whenever we encounter an opening bracket, we push it onto our stack. Whenever we hit a closing bracket, we check: is the stack empty? Does the top of the stack match this closing bracket? If not, it is invalid! If the stack is completely empty at the end, the string is perfectly balanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*zUb_d64NC7baycJIO0NYFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*aWK2wZjSCiZukSkHvMRuqg.png" /><figcaption><em>Figure 6: Validating nested bracket syntax with a LIFO stack across all 8 edge cases in VS Code.</em></figcaption></figure><p><strong>Problem 7 (p07): Daily Temperatures — Waiting for Hot Lagos Sun (daily_temperatures)</strong></p><p>The Challenge: Given a list of daily temperatures, return an array where each position tells you how many days you must wait until a warmer temperature arrives. If no warmer day exists, return 0.</p><p>How We Solved It: Brute-forcing this with two nested loops takes O(N²) time, if you have 50,000 days of data, your computer will freeze! Instead, we deployed a Monotonic Decreasing Stack storing indices. As we walk through each day, if today’s temperature is hotter than the days waiting on our stack, we pop those cooler days and calculate their wait time: wait = today_index — popped_index! Every day is pushed and popped at most once: pure O(N) linear time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*LK8RoUJQP0G6-n6OdS1XTw.png" /><figcaption><em>Figure 7: Monotonic stack resolving warmer temperature wait times in linear O(N) time in VS Code.</em></figcaption></figure><p><strong>Problem 8 (p08): Flatten Nested Lists — Unpacking Wedding Hampers (flatten)</strong></p><p>The Challenge: Given an arbitrarily nested list of elements (e.g. [1, [2, [3, 4], 5], 6]), extract all non-list items into a single flat list in exact left-to-right order.</p><p>How We Solved It: Think of unwrapping a lavish Nigerian wedding gift hamper! You open the main basket, find a box, open that box, find smaller packages inside, and keep unwrapping until you reach the actual perfumes and chocolates! We used Recursion: if an item is a list, we call flatten() on it; if it is an atomic value, we append it to our result list. Clean, elegant, and handles infinite nesting depths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*fZTNFlTssVVNTmHtmGUrMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5mKw68I1esLhpKGNKi9xOQ.png" /><figcaption><em>Figure 8: Recursive list flattening extracting atomic values across complex nested structures in VS Code.</em></figcaption></figure><p><strong>Problem 9 (p09): First &amp; Last Position — Binary Search (search_range)</strong></p><p>The Challenge: Given a sorted array of integers that may contain duplicates and a target value, find the starting and ending index of that target in O(log N) runtime.</p><p>How We Solved It: Linear scanning takes O(N) time. To achieve O(log N), we ran two separate Binary Searches: one to find the first occurrence (when nums[mid] == target, we record mid and continue searching left: high = mid — 1), and a second to find the last occurrence (when nums[mid] == target, we record mid and continue searching right: low = mid + 1). It was so blistering fast it completed in 4.7 milliseconds, locking in our 3rd speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_a7sQ8L7zcWFrblAYVuk2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*HZoO8d78lnBAQHTbW31DKQ.png" /><figcaption><em>Figure 9: Dual binary search in VS Code finding target boundaries in 4.7 ms with +1 speed bonus point.</em></figcaption></figure><p><strong>Problem 10 (p10): Ship Capacity — Packing Alaba Trucks (ship_capacity)</strong></p><p>The Challenge: Given a list of parcel weights to be shipped in order and an integer days, find the minimum conveyor/ship capacity required so that all parcels can be delivered within days days.</p><p>How We Solved It: This is Binary Search on the Answer Space! What is the absolute smallest capacity possible? The weight of the heaviest single parcel (max(weights)). What is the largest capacity needed? The total sum of all parcels (sum(weights)). Instead of testing every capacity one by one, we test the midpoint mid. If a helper function can_ship(mid) succeeds in delivering within days days, we try an even smaller capacity (high = mid — 1). If it fails, we need a larger capacity (low = mid + 1). Total runtime: O(N log(sum of weights)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*33-x-lL41bUr9pfn1OXVQA.png" /></figure><figure><img alt="VS Code notebook output displaying ship_capacity passing all 7 test cases." src="https://cdn-images-1.medium.com/max/975/1*CqW4f-y_moPGAVYU0aZg4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*toIWcvUTerlR_6Q1KRePKA.png" /><figcaption><em>Figure 10: Binary search on the answer space determining minimum viable delivery capacity in VS Code.</em></figcaption></figure><p><strong>5. The Big Test: 10/10 Tests Passed, Lightning Speed, and a 100% Scorecard!</strong></p><p>After writing all 10 solutions, it was time for the moment of truth: running our fellowship’s master grading function score_all()! You know that nervous excitement when you press Shift + Enter, praying that no rogue bugs pop up? Look at what our terminal output returned:</p><p>· <strong>• 100% Correctness: </strong>All 10 problems passed every single unit test suite (7/7, 8/8, 6/6, 5/5) without a single failure!</p><p>· <strong>• 3/3 Speed Bonuses: </strong>All 3 speed benchmarks (pair_with_sum in 3.4 ms, longest_consecutive in 10.6 ms, search_range in 4.7 ms) easily beat the 50 ms limit!</p><p>· <strong>• The Final Verdict: </strong>TOTAL: 29.0 / 29 (100%) -&gt; Distinction! Across Arrays, Hashing, Linked Lists, Stacks, Recursion, and Binary Search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*4oCY1Plrvd_T3WVOcodFwg.png" /></figure><figure><img alt="Full grade breakdown table in VS Code showing 29 out of 29 points achieved with Distinction certification and all speed bonuses active." src="https://cdn-images-1.medium.com/max/875/1*e232tvvN8phPVjDgQUWaKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*d1l6LkyNtK9CiJqJsDb0Kg.png" /><figcaption><em>Figure 11: The official automated evaluation grade table in VS Code awarding a perfect 29.0 / 29.0 (100%) Distinction.</em></figcaption></figure><p><strong>6. Thinking Like Senior Engineers: Our Written Reflections</strong></p><p>Writing code that passes tests is fantastic, but understanding the architectural trade-offs behind your choices is what separates a code monkey from a true engineer. In Cell 29 of our notebook, we documented in-depth reflections on six critical questions:</p><p>· <strong>1. Sliding Window Arithmetic (Problem 1 vs Brute Force): </strong>In Problem 1, recalculating k elements took O(N · k) time. Our sliding window maintains the running sum incrementally, dropping update time to O(1) per step. For a dataset of 1,000,000 rows with k = 30, that slashes operations from 30,000,000 down to 1,000,000.</p><p>· <strong>2. When Two Pointers Beat Hash Maps (Problem 2): </strong>In Problem 2, pre-sorted data gave us directional certainty! We could move left and right pointers inward in O(1) space. If the array had not been sorted, sorting it first would have cost O(N log N) time, making a hash map O(N) lookup preferable.</p><p>· <strong>3. Guarding the Sequence Starter (Problem 4): </strong>In Problem 4, checking if (num — 1) is absent ensures we only initiate counting loops from sequence captains. This guarantees that each number is visited at most twice, maintaining O(N) linear time.</p><p>· <strong>4. Monotonic Stack vs Nested Loops (Problem 7): </strong>In Problem 7, a naive nested loop takes O(N²) time. By using a monotonic stack, each temperature index is pushed onto the stack once and popped at most once. The total operations across the entire array are at most 2N, guaranteeing O(N) linear performance.</p><p>· <strong>5. Monotonic Feasibility in Binary Search (Problem 10): </strong>In Problem 10, binary search works because capacity is monotonic: if capacity C can ship the parcels within D days, any capacity greater than C can also do it. This monotonic property allows us to discard half the search space at each iteration in O(log(range)) time.</p><p>· <strong>6. Real-World Pipeline Scalability: </strong>In enterprise streaming pipelines (such as fraud detection or real-time payment reconciliation), algorithms with O(N²) complexity create fatal bottlenecks and cause memory exhaustion. Designing with O(N) time and O(1) space keeps infrastructure lean and highly resilient.</p><p><strong>7. The SQL Bridge: Bringing DSA Into Real Cohort Databases!</strong></p><p>Now, here is the secret that many people miss: Data Structures and Algorithms are NOT just for Python interview challenges! Every single concept we mastered in Python lives directly inside modern SQL database engines. In Part 2 of our project, we connected directly to our cohort SQL Server database and tackled four real-world data engineering challenges across cohort schemas week06 and week09:</p><p><strong>Task 1 (s01): Hashing in SQL — Group By Value Counting</strong></p><p>What does Python’s Counter do? It groups records and tallies occurrences using a hash table under the hood. In SQL, we replicated this exact behavior on our London 2014 temperature records (week06.london_2014) to count how many days recorded each maximum temperature, filtering for temperatures with at least 20 occurrences. Passed cleanly with 10 rows returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*jn3ROjPtLWhKgtkztXZ3zQ.png" /></figure><figure><img alt="VS Code screenshot showing SQL query and grouped temperature frequency table passing autograder with 10 rows." src="https://cdn-images-1.medium.com/max/975/1*dWvc8PC097op9jnp9Duecg.png" /><figcaption><em>Figure 12: SQL Task 1 (s01) replicating Python hash counting with GROUP BY and HAVING in VS Code.</em></figcaption></figure><p><strong>Task 2 (s02): Searching with NOT EXISTS — Short-Circuit Efficiency</strong></p><p>How do we find new 2015 UK milk trade partners that never existed in the 2014 records? We used NOT EXISTS! Why? Because NOT EXISTS behaves like a smart short-circuit linear search: the microsecond SQL finds a single matching record, it halts execution immediately! Furthermore, unlike NOT IN, NOT EXISTS is immune to NULL value traps. Passed cleanly with 6 rows returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*B7ohqAQDAp3p3biFFFbbmg.png" /></figure><figure><img alt="VS Code SQL query and dataframe output table showing new UK milk trade partners with green PASS tag." src="https://cdn-images-1.medium.com/max/975/1*jcdo5J6km9rvZuX6996BrQ.png" /><figcaption><em>Figure 13: SQL Task 2 (s02) using NOT EXISTS in VS Code to identify new 2015 UK milk export partners.</em></figcaption></figure><p><strong>Task 3 (s03): Prefix Sums &amp; Differencing with LAG in SQL</strong></p><p>In Python, we used prefix sums to compute range totals in O(1) time. In SQL, we computed running monthly export totals using SUM(exports) OVER (ORDER BY period ROWS UNBOUNDED PRECEDING). We then calculated rolling 3-month sums in O(1) time simply by subtracting the prefix sum from 3 months prior using LAG(running_total, 3, 0)! Passed with precision across all 12 months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*t4al-CZl-K7O4jjHfO06Lw.png" /></figure><figure><img alt="VS Code query and dataframe table displaying 12 monthly export rows with running totals and 3-month rolling sums." src="https://cdn-images-1.medium.com/max/975/1*MNEtFKtgSCg1nYyZhTjUGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*mjIAZ8CISqJ2_VFi0nYwgQ.png" /><figcaption><em>Figure 14: SQL Task 3 (s03) computing running totals and rolling 3-month prefix differences in VS Code.</em></figcaption></figure><p>How do we find the warmest continuous 7-day period in 2014 across six global cities (Beijing, Brasilia, Cape Town, Delhi, London, Moscow)? We translated our sliding window concept directly into SQL window frames using AVG(1.0 * temp) OVER (PARTITION BY city ORDER BY day ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING)! We filtered out partial windows and ranked peak heat waves with ROW_NUMBER().</p><p><em>📷</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DbUQKfOktdGNkxSaJ964aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FxPt_RE-o9UCKpjNAGce9w.png" /></figure><p><em>Figure 15: SQL Task 4 (s04) finding peak 7-day warming streaks across 6 global capital cities in VS Code.</em></p><p>🏷️ Medium Alt Text: VS Code SQL query and result table showing warmest 7-day windows for Beijing, Brasilia, Cape Town, Delhi, London, and Moscow.</p><p><strong>The SQL Autograder Scorecard: 4 / 4 Tasks Passed (100%)</strong></p><p>When we executed p.score(), the cohort database autograder verified our query cryptographic signatures and awarded a perfect 100% pass mark across all four data engineering challenges.</p><p><em>📷 Figure 16: Automated SQL practice grading suite confirming 4 / 4 tasks passed in VS Code.</em></p><p>🏷️ Medium Alt Text: VS Code terminal output showing Practice Score: 4 / 4 tasks passed with all green PASS confirmations.</p><p><strong>8. Lessons Learned: Stumbling Into Potholes and Bouncing Back</strong></p><p>Let us be real with each other: nobody becomes confident in tech without stumbling into a few potholes along the way! Here are the real challenges we faced this week, and how we tackled them together:</p><p>· <strong>• The Off-by-One Sliding Window Trap: </strong>When writing Problem 1 (max_window_sum), our first attempt had an off-by-one boundary error where we missed the final day of the array. We fixed this by sketching the indices on paper and using range(k, len(nums)). Visualizing pointers with a pen and notepad is a superpower.</p><p>· <strong>• The Nested Window Function Shock: </strong>In SQL Task 3, we initially tried writing LAG(SUM(…) OVER (…)) directly. SQL Server immediately barked at us: ‘Windowed functions cannot be used in the context of another windowed function!’ We took a sip of water, stepped back, and split the query into two clean Common Table Expressions (CTEs): one to compute the running total, and a second to apply the LAG() subtraction. That solved it instantly.</p><p>· <strong>• The Table Name Detective Work: </strong>When querying city weather tables, we initially looked for week06.beijing_2014, but the database returned an error that the table did not exist. By inspecting the cohort schema, we discovered the tables had airport code suffixes (e.g. beijing_pek_2014, moscow_svo_2014). Never guess table names — always verify with metadata queries.</p><p><strong>9. Let Us Connect: Our Community Challenge For You!</strong></p><p>If you have read all the way to this point with us, give yourself a big round of applause! You have officially demystified Data Structures, Algorithms, and SQL without shedding tears, and you can now walk into any technical room with your head held high.</p><p>Now, before you go, we want to hear your voice! We have a fun community question for you to answer in the comments below:</p><p><strong>COMMUNITY CHALLENGE OF THE WEEK<br> </strong><em>Imagine you are building a real-time leaderboard for a mobile fintech app in Nigeria that processes millions of transactions daily. You want to display the Top 10 highest spenders of the day in real time. Would you sort the entire database every 5 minutes (O(N log N)), or would you use a Min-Heap of size 10 (O(N log 10))? Tell us in the comments what approach you would choose and why.</em></p><p>Drop your thoughts in the comment section below, let us debate and learn together. If this article made Big-O and DSA click for you, kindly share it with a friend who is currently wrestling with coding concepts. Until our next project, keep coding with joy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5d4e6c3b57b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Owambe Weddi­­­ng Greetings to O(1) Lookups: How We Conquered Data Structures, Algorithms, and…]]></title>
            <link>https://medium.com/@faruqraji604/from-owambe-weddi-ng-greetings-to-o-1-lookups-how-we-conquered-data-structures-algorithms-and-4410d153c126?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4410d153c126</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 07:57:21 GMT</pubDate>
            <atom:updated>2026-11-27T07:57:21.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Owambe Weddi­­­ng Greetings to O(1) Lookups: How We Conquered Data Structures, Algorithms, and SQL Without Shedding Tears!</h3><h3>­­<em>A beginner survival guide for anyone who used to run away from DSA and Big-O notation. Grab your chin-chin and cold Zobo drink, let us break it down together.</em></h3><p>DataraFlow Week 11–12</p><p><strong>1. My People, Make We Settle Down: The DSA Panic is Over!</strong></p><p>Let us be honest with ourselves for a moment. You know that quiet, trembling panic that hits your chest whenever someone in tech mentions ‘Data Structures and Algorithms’ or ‘Big-O notation’? Ehen! That cold sweat where your heart starts doing rapid legwork, as if you owe the entire neighborhood money? That was exactly me and many of us when Week 11 of our data fellowship kicked off!</p><p>For a very long time, society made us believe that Data Structures and Algorithms (DSA) was an exclusive club reserved for mathematicians with three PhDs or people who dream in binary code. Whenever we opened those classic textbook tutorials, we saw scary Greek symbols, complicated math equations, and intimidating diagrams that looked like ancient Egyptian hieroglyphics. Before you knew it, we would gently close our laptops, say ‘God forbid’, and go and fry plantain. <em>LOL, E GO DO BE THAT!!!</em></p><p>But you see this week? We had a massive breakthrough, and I want us to celebrate it together! We discovered that Data Structures and Algorithms are not witchcraft at all. In fact, no be juju(magic), na everyday common sense! DSA is simply about saving our computer from unnecessary suffering, the exact same way we make smart decisions every single day in our homes, at market squares, and at family parties.</p><p>In this post, we are going to walk side-by-side through our entire journey: how we decoded Big-O using relatable Nigerian life, how we solved all 10 algorithmic puzzles step-by-step with zero fluff, how our code smashed all speed benchmarks in under 11 milliseconds, and how we took those exact same algorithmic superpowers straight into our SQL database. Come along with me, I promise you will laugh, learn, and never fear DSA again.</p><p><strong>2. Big-O Notation: The Nigerian Owambe Wedding Guide</strong></p><p>Before we write a single line of Python code, we must settle our score with the famous boss of computer science: Big-O notation. What is Big-O really? Strip away all the academic grammar, and Big-O is simply asking one practical question: As the amount of work grows bigger, how much more sweat will our computer suffer to finish it?</p><p>To make this super crystal clear and easy to digest, let us imagine ourselves attending a colorful, bustling Nigerian Owambe wedding reception on a Saturday afternoon.</p><p><strong>O(1) — Constant Time: Spotting the Couple on the High Table</strong></p><p>Imagine we step into a wedding marquee with 500 guests sitting under canopies. If someone asks us: ‘Where are the bride and groom?’, do we need to walk around and inspect every single chair in the hall? Never! All we do is look directly at the glittering High Table on the stage, gbem! We see them immediately. Whether only 50 guests show up or a massive crowd of 5,000 people storms the reception, it takes us the exact same 1 second to spot the couple. That is O(1) Constant Time. Zero extra sweat, regardless of crowd size!</p><p><strong>O(N) — Linear Time: Mum’s Famous ‘Go and Greet Everybody’ Command</strong></p><p>Now, contrast that with another very familiar scenario. Say I arrive at a Nigerian wedding reception with 200 guests, and my Nigerian mum tells me: ‘Go and greet everybody one by one’, funny that’s Nigerian mum for us! If there are 200 people, I greet 200 times. If 500 people come, I greet 500 times. If 1,000 guests arrive, my poor knees must bend down and greet 1,000 times! The work grows directly with the crowd.</p><p>That is O(N) Linear Time! If the crowd doubles, our knee bending doubles. If the input size N triples, our computer’s work triples proportionally. Fair and manageable, but the stress increases steadily.</p><p><strong>O(N²) — Quadratic Time: The Handshake Nightmare (Avoid Like Lagos Traffic!)</strong></p><p>Now, imagine the ultimate nightmare. Imagine my mum says: ‘Faruq, not only will you greet every guest, but for every single person you greet, you must introduce them to every other person sitting in the hall!’ Jesus is Lord! 200 guests greeting 200 other guests? That is 200 × 200 = 40,000 handshakes! If 500 guests attend, that becomes 250,000 handshakes! By the time we finish, the wedding reception is over, the caterer has packed the jollof rice coolers, the MC has gone home, and our knees have retired from service! That is O(N²) Quadratic Time, the terrible result of nested loops. We must avoid it like the third mainland bridge at 6:00 PM on a rainy Monday!</p><p><strong>O(log N) — Logarithmic Time: The Balogun Market Shoe Bargaining</strong></p><p>Have you ever bargained for shoes in Balogun market? The trader calls out: ‘N50,000!’ You immediately smile and counter with: ‘N10,000!’ He says: ‘Bring N35,000!’ You say: ‘Let us meet in the middle at N22,000!’ At every single offer, we cut the gap directly in half! Instead of counting every single naira one by one from 10,000 to 50,000, we zero in on the final price in just four or five quick splits! That is O(log N) Logarithmic Time. It is the secret power behind Binary Search.</p><p><strong>THE OWAMBE RULE OF COMPUTATION<br> </strong><em>Always remember: O(1) is instant like looking at the High Table; O(log N) cuts the crowd in half repeatedly; O(N) is greeting guests one by one; and O(N²) is greeting everyone and introducing them to everyone else! Whenever we write code, our mission is to pull our solutions away from O(N²) and bring them down to O(N) or O(log N)!</em></p><p><strong>3. The Toolbelt: Meet Our Everyday Data Structures</strong></p><p>Just like a master craftsman has specific tools in their box, we as data professionals have data structures. Each one has a specific personality and strength:</p><p>· <strong>1. Arrays &amp; Lists: </strong>Numbered chairs under the canopy! If you give me index 4, I jump straight to chair 4 in O(1) time. But if you tell me to look for Uncle Segun among 1,000 unlabelled chairs, I must inspect chair by chair in O(N) time.</p><p>· <strong>2. Hash Maps (Dictionaries): </strong>Mama Put having your name and your exact favorite order memorized! The moment you show up, she serves you your hot plate immediately in O(1) time. In Python, this is our dictionary, and it is our #1 weapon against sluggish code.</p><p>· <strong>3. Sets: </strong>The eagle-eyed bouncer at the wedding gate holding the exclusive VIP list. He ensures no duplicate gatecrashers enter, and checks whether your name is on the list in O(1) blink-of-an-eye speed.</p><p>· <strong>4. Linked Lists: </strong>A line of fuel kegs tied together with rope! Each keg knows only who is in front of it. Inserting a new keg in the middle is effortless, but jumping to the 10th keg means walking the rope link by link.</p><p>· <strong>5. Stacks: </strong>The pile of hot plates in Mama Put’s kitchen! Last plate placed on top is the First plate picked up (LIFO). Perfect for undo operations and validating nested brackets.</p><p>· <strong>6. Deques: </strong>The double-ended Danfo bus where passengers can politely board and alight from both the front and back doors in O(1) time without anyone climbing over seats.</p><p><strong>4. Step-by-Step Walkthrough: Conquering the 10 Algorithmic Tasks</strong></p><p>Now, let us get our hands dirty with the actual code! For our week 11 take-home project, we were handed 10 algorithmic problems covering the full spectrum of data structures. We structured every single solution inside our Jupyter Notebook with three clear parts: what the task asked, our first-person commentary on why we wrote the code, and an explanation of the underlying mechanics.</p><p><strong>Problem 1 (p01): Best K-Day Sales — The Jumia Sliding Window (max_window_sum)</strong></p><p>The Challenge: Imagine you manage an e-commerce store like Jumia or Konga. Given daily revenue numbers and an integer k, find the maximum sales revenue earned across any consecutive k days in O(N) time.</p><p>How We Solved It: A naive coder would recalculate the sum of all k days from scratch every single morning, that is O(N · k) sweat! Instead, we used a Sliding Window. We sum the first k days. Then, as our window slides forward each day, we subtract the day that just slipped out of the back, and add the new day coming in through the front! Window updates happen in O(1) time, completing the entire year in a single O(N) pass!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1RmRY9vSiSBDNIdWCpXIJQ.png" /></figure><figure><img alt="VS Code screenshot showing problem prompt, Python code for max_window_sum, and output confirming All 7 tests passed." src="https://cdn-images-1.medium.com/max/975/1*YlTNu6WEIP0P3lhtORPVhw.png" /><figcaption><em>Figure 1: Executing max_window_sum inside VS Code with O(N) sliding window and verifying all 7 unit tests pass.</em></figcaption></figure><p><strong>Problem 2 (p02): Pair with Sum K — The Danfo Conductor Two Pointers (pair_with_sum)</strong></p><p>The Challenge: Given an already sorted array of integers and a target sum, find two indices whose values sum up to the target in O(N) time and strictly O(1) auxiliary space (no extra dictionaries allowed!).</p><p>How We Solved It: Because the list is pre-sorted, we deployed two pointers! Imagine two bus conductors: one at the front seat (smallest value, left = 0) and one at the back seat (largest value, right = len — 1). We sum their values. If the sum is too small, the front conductor steps forward. If the sum is too large, the back conductor steps backward. They meet in the middle without allocating a single byte of extra memory. Our code was so fast it crushed the speed benchmark in just 3.4 milliseconds (limit was 50 ms), earning us a speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1iZLmRhiO2VIoSHO9lH8Gw.png" /></figure><figure><img alt="VS Code editor showing pair_with_sum code with output indicating All 7 tests passed and speed test passed in 3.4 ms with +1 bonus point." src="https://cdn-images-1.medium.com/max/975/1*nd1kcFBOVBB34ZAM7J58mg.png" /><figcaption><em>Figure 2: Verifying pair_with_sum in VS Code with two pointers, passing all 7 tests and smashing the speed bonus in 3.4 ms.</em></figcaption></figure><p><strong>Problem 3 (p03): Group Anagrams — Sorting Ingredients into Buckets (group_anagrams)</strong></p><p>The Challenge: Given a list of words, group words that are anagrams of each other together into clusters (e.g. ‘listen’ and ‘silent’ have the exact same letters).</p><p>How We Solved It: Think of preparing jollof rice. Whether you chop onions first or tomatoes first, the raw ingredients in the pot are identical! For each word, we sort its letters alphabetically and convert them into a tuple, like tuple(sorted(‘silent’)) -&gt; (‘e’, ‘i’, ‘l’, ’n’, ‘s’, ‘t’). We use this sorted tuple as the universal key in a dictionary, appending every matching word to that key’s bucket. Grouping happens in O(N · L log L) time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*LvhLOV7JIjWkgKhcI_8INg.png" /></figure><figure><img alt="VS Code screenshot demonstrating group_anagrams passing all 7 test cases cleanly." src="https://cdn-images-1.medium.com/max/975/1*6C1Xx6HumruPyXYa7g9s-A.png" /><figcaption><em>Figure 3: Grouping words into anagram clusters using character tuple dictionary hashing in VS Code.</em></figcaption></figure><p>The Challenge: Given an unsorted array of numbers, find the length of the longest streak of consecutive numbers (e.g. [100, 4, 200, 1, 3, 2] contains [1, 2, 3, 4], length 4). You must do it in O(N) average time, meaning you are strictly forbidden from sorting the array.</p><p>How We Solved It: We dumped all numbers into a Python set for O(1) instant lookups. Now, here is the genius move: How do we know if a number is the true leader of a streak? If num — 1 is NOT in the set! If num — 1 exists, we ignore it, because it is part of a streak that started earlier. But if num — 1 is absent, this number is the captain! We then count upwards (num + 1, num + 2…) until the streak breaks. This guarantees each number is touched at most twice. Our solution was so blazing fast it finished in 10.6 milliseconds, earning our second speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Sz08O-MDdAhks8Khx_cl9Q.png" /></figure><figure><img alt="VS Code editor showing longest_consecutive code and output confirming 7/7 tests passed with speed test passed in 10.6 ms (+1 bonus point)." src="https://cdn-images-1.medium.com/max/975/1*p2r9ERCfcHlXFKHtdRP8bQ.png" /><figcaption><em>Figure 4: Hash set streak search in VS Code finding longest consecutive runs in O(N) time and earning speed bonus in 10.6 ms.</em></figcaption></figure><p><strong>Problem 5 (p05): Reverse a Linked List — Flipping the Queue In-Place (reverse_list)</strong></p><p>The Challenge: Given the head of a singly linked list, reverse the list in-place so that the last node becomes the head, using O(1) auxiliary space.</p><p>How We Solved It: Imagine a line of people holding hands, facing right. To reverse them, we walk down the line using three pointers: prev, curr, and next_node. At every step, we save the next person in line, turn curr.next backward to point to prev, move prev forward to curr, and advance curr to next_node. By the time curr reaches None, prev is holding the new head of the reversed list! Zero new nodes created, pure O(N) time and O(1) space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*MR8HFQEm0ffWJzPrAxi9Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cbaFwpaDAqxzt_JLB-pazw.png" /><figcaption><em>Figure 5: Reversing singly linked list nodes in-place using pointer rewiring in VS Code.</em></figcaption></figure><p><strong>Problem 6 (p06): Balanced Parentheses — Mama Put’s Nested Bowls (is_balanced)</strong></p><p>The Challenge: Given a string containing brackets, parentheses, and braces (‘()’, ‘[]’, ‘{}’), determine if all opening brackets are closed in the correct nested order.</p><p>How We Solved It: Think of Mama Put nesting her plastic bowls. The last bowl you place inside must be the first bowl you remove! We used a Stack (LIFO). Whenever we encounter an opening bracket, we push it onto our stack. Whenever we hit a closing bracket, we check: is the stack empty? Does the top of the stack match this closing bracket? If not, it is invalid! If the stack is completely empty at the end, the string is perfectly balanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*zUb_d64NC7baycJIO0NYFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*aWK2wZjSCiZukSkHvMRuqg.png" /><figcaption><em>Figure 6: Validating nested bracket syntax with a LIFO stack across all 8 edge cases in VS Code.</em></figcaption></figure><p><strong>Problem 7 (p07): Daily Temperatures — Waiting for Hot Lagos Sun (daily_temperatures)</strong></p><p>The Challenge: Given a list of daily temperatures, return an array where each position tells you how many days you must wait until a warmer temperature arrives. If no warmer day exists, return 0.</p><p>How We Solved It: Brute-forcing this with two nested loops takes O(N²) time, if you have 50,000 days of data, your computer will freeze! Instead, we deployed a Monotonic Decreasing Stack storing indices. As we walk through each day, if today’s temperature is hotter than the days waiting on our stack, we pop those cooler days and calculate their wait time: wait = today_index — popped_index! Every day is pushed and popped at most once: pure O(N) linear time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*LK8RoUJQP0G6-n6OdS1XTw.png" /><figcaption><em>Figure 7: Monotonic stack resolving warmer temperature wait times in linear O(N) time in VS Code.</em></figcaption></figure><p><strong>Problem 8 (p08): Flatten Nested Lists — Unpacking Wedding Hampers (flatten)</strong></p><p>The Challenge: Given an arbitrarily nested list of elements (e.g. [1, [2, [3, 4], 5], 6]), extract all non-list items into a single flat list in exact left-to-right order.</p><p>How We Solved It: Think of unwrapping a lavish Nigerian wedding gift hamper! You open the main basket, find a box, open that box, find smaller packages inside, and keep unwrapping until you reach the actual perfumes and chocolates! We used Recursion: if an item is a list, we call flatten() on it; if it is an atomic value, we append it to our result list. Clean, elegant, and handles infinite nesting depths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*fZTNFlTssVVNTmHtmGUrMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5mKw68I1esLhpKGNKi9xOQ.png" /><figcaption><em>Figure 8: Recursive list flattening extracting atomic values across complex nested structures in VS Code.</em></figcaption></figure><p><strong>Problem 9 (p09): First &amp; Last Position — Binary Search (search_range)</strong></p><p>The Challenge: Given a sorted array of integers that may contain duplicates and a target value, find the starting and ending index of that target in O(log N) runtime.</p><p>How We Solved It: Linear scanning takes O(N) time. To achieve O(log N), we ran two separate Binary Searches: one to find the first occurrence (when nums[mid] == target, we record mid and continue searching left: high = mid — 1), and a second to find the last occurrence (when nums[mid] == target, we record mid and continue searching right: low = mid + 1). It was so blistering fast it completed in 4.7 milliseconds, locking in our 3rd speed bonus point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_a7sQ8L7zcWFrblAYVuk2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*HZoO8d78lnBAQHTbW31DKQ.png" /><figcaption><em>Figure 9: Dual binary search in VS Code finding target boundaries in 4.7 ms with +1 speed bonus point.</em></figcaption></figure><p><strong>Problem 10 (p10): Ship Capacity — Packing Alaba Trucks (ship_capacity)</strong></p><p>The Challenge: Given a list of parcel weights to be shipped in order and an integer days, find the minimum conveyor/ship capacity required so that all parcels can be delivered within days days.</p><p>How We Solved It: This is Binary Search on the Answer Space! What is the absolute smallest capacity possible? The weight of the heaviest single parcel (max(weights)). What is the largest capacity needed? The total sum of all parcels (sum(weights)). Instead of testing every capacity one by one, we test the midpoint mid. If a helper function can_ship(mid) succeeds in delivering within days days, we try an even smaller capacity (high = mid — 1). If it fails, we need a larger capacity (low = mid + 1). Total runtime: O(N log(sum of weights)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*33-x-lL41bUr9pfn1OXVQA.png" /></figure><figure><img alt="VS Code notebook output displaying ship_capacity passing all 7 test cases." src="https://cdn-images-1.medium.com/max/975/1*CqW4f-y_moPGAVYU0aZg4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*toIWcvUTerlR_6Q1KRePKA.png" /><figcaption><em>Figure 10: Binary search on the answer space determining minimum viable delivery capacity in VS Code.</em></figcaption></figure><p><strong>5. The Big Test: 10/10 Tests Passed, Lightning Speed, and a 100% Scorecard!</strong></p><p>After writing all 10 solutions, it was time for the moment of truth: running our fellowship’s master grading function score_all()! You know that nervous excitement when you press Shift + Enter, praying that no rogue bugs pop up? Look at what our terminal output returned:</p><p>· <strong>• 100% Correctness: </strong>All 10 problems passed every single unit test suite (7/7, 8/8, 6/6, 5/5) without a single failure!</p><p>· <strong>• 3/3 Speed Bonuses: </strong>All 3 speed benchmarks (pair_with_sum in 3.4 ms, longest_consecutive in 10.6 ms, search_range in 4.7 ms) easily beat the 50 ms limit!</p><p>· <strong>• The Final Verdict: </strong>TOTAL: 29.0 / 29 (100%) -&gt; Distinction! Across Arrays, Hashing, Linked Lists, Stacks, Recursion, and Binary Search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*4oCY1Plrvd_T3WVOcodFwg.png" /></figure><figure><img alt="Full grade breakdown table in VS Code showing 29 out of 29 points achieved with Distinction certification and all speed bonuses active." src="https://cdn-images-1.medium.com/max/875/1*e232tvvN8phPVjDgQUWaKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*d1l6LkyNtK9CiJqJsDb0Kg.png" /><figcaption><em>Figure 11: The official automated evaluation grade table in VS Code awarding a perfect 29.0 / 29.0 (100%) Distinction.</em></figcaption></figure><p><strong>6. Thinking Like Senior Engineers: Our Written Reflections</strong></p><p>Writing code that passes tests is fantastic, but understanding the architectural trade-offs behind your choices is what separates a code monkey from a true engineer. In Cell 29 of our notebook, we documented in-depth reflections on six critical questions:</p><p>· <strong>1. Sliding Window Arithmetic (Problem 1 vs Brute Force): </strong>In Problem 1, recalculating k elements took O(N · k) time. Our sliding window maintains the running sum incrementally, dropping update time to O(1) per step. For a dataset of 1,000,000 rows with k = 30, that slashes operations from 30,000,000 down to 1,000,000.</p><p>· <strong>2. When Two Pointers Beat Hash Maps (Problem 2): </strong>In Problem 2, pre-sorted data gave us directional certainty! We could move left and right pointers inward in O(1) space. If the array had not been sorted, sorting it first would have cost O(N log N) time, making a hash map O(N) lookup preferable.</p><p>· <strong>3. Guarding the Sequence Starter (Problem 4): </strong>In Problem 4, checking if (num — 1) is absent ensures we only initiate counting loops from sequence captains. This guarantees that each number is visited at most twice, maintaining O(N) linear time.</p><p>· <strong>4. Monotonic Stack vs Nested Loops (Problem 7): </strong>In Problem 7, a naive nested loop takes O(N²) time. By using a monotonic stack, each temperature index is pushed onto the stack once and popped at most once. The total operations across the entire array are at most 2N, guaranteeing O(N) linear performance.</p><p>· <strong>5. Monotonic Feasibility in Binary Search (Problem 10): </strong>In Problem 10, binary search works because capacity is monotonic: if capacity C can ship the parcels within D days, any capacity greater than C can also do it. This monotonic property allows us to discard half the search space at each iteration in O(log(range)) time.</p><p>· <strong>6. Real-World Pipeline Scalability: </strong>In enterprise streaming pipelines (such as fraud detection or real-time payment reconciliation), algorithms with O(N²) complexity create fatal bottlenecks and cause memory exhaustion. Designing with O(N) time and O(1) space keeps infrastructure lean and highly resilient.</p><p><strong>7. The SQL Bridge: Bringing DSA Into Real Cohort Databases!</strong></p><p>Now, here is the secret that many people miss: Data Structures and Algorithms are NOT just for Python interview challenges! Every single concept we mastered in Python lives directly inside modern SQL database engines. In Part 2 of our project, we connected directly to our cohort SQL Server database and tackled four real-world data engineering challenges across cohort schemas week06 and week09:</p><p><strong>Task 1 (s01): Hashing in SQL — Group By Value Counting</strong></p><p>What does Python’s Counter do? It groups records and tallies occurrences using a hash table under the hood. In SQL, we replicated this exact behavior on our London 2014 temperature records (week06.london_2014) to count how many days recorded each maximum temperature, filtering for temperatures with at least 20 occurrences. Passed cleanly with 10 rows returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*jn3ROjPtLWhKgtkztXZ3zQ.png" /></figure><figure><img alt="VS Code screenshot showing SQL query and grouped temperature frequency table passing autograder with 10 rows." src="https://cdn-images-1.medium.com/max/975/1*dWvc8PC097op9jnp9Duecg.png" /><figcaption><em>Figure 12: SQL Task 1 (s01) replicating Python hash counting with GROUP BY and HAVING in VS Code.</em></figcaption></figure><p><strong>Task 2 (s02): Searching with NOT EXISTS — Short-Circuit Efficiency</strong></p><p>How do we find new 2015 UK milk trade partners that never existed in the 2014 records? We used NOT EXISTS! Why? Because NOT EXISTS behaves like a smart short-circuit linear search: the microsecond SQL finds a single matching record, it halts execution immediately! Furthermore, unlike NOT IN, NOT EXISTS is immune to NULL value traps. Passed cleanly with 6 rows returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*B7ohqAQDAp3p3biFFFbbmg.png" /></figure><figure><img alt="VS Code SQL query and dataframe output table showing new UK milk trade partners with green PASS tag." src="https://cdn-images-1.medium.com/max/975/1*jcdo5J6km9rvZuX6996BrQ.png" /><figcaption><em>Figure 13: SQL Task 2 (s02) using NOT EXISTS in VS Code to identify new 2015 UK milk export partners.</em></figcaption></figure><p><strong>Task 3 (s03): Prefix Sums &amp; Differencing with LAG in SQL</strong></p><p>In Python, we used prefix sums to compute range totals in O(1) time. In SQL, we computed running monthly export totals using SUM(exports) OVER (ORDER BY period ROWS UNBOUNDED PRECEDING). We then calculated rolling 3-month sums in O(1) time simply by subtracting the prefix sum from 3 months prior using LAG(running_total, 3, 0)! Passed with precision across all 12 months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*t4al-CZl-K7O4jjHfO06Lw.png" /></figure><figure><img alt="VS Code query and dataframe table displaying 12 monthly export rows with running totals and 3-month rolling sums." src="https://cdn-images-1.medium.com/max/975/1*MNEtFKtgSCg1nYyZhTjUGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*mjIAZ8CISqJ2_VFi0nYwgQ.png" /><figcaption><em>Figure 14: SQL Task 3 (s03) computing running totals and rolling 3-month prefix differences in VS Code.</em></figcaption></figure><p><strong>Task 4 (s04): Sliding Windows on Global Cities in SQL</strong></p><p>How do we find the warmest continuous 7-day period in 2014 across six global cities (Beijing, Brasilia, Cape Town, Delhi, London, Moscow)? We translated our sliding window concept directly into SQL window frames using AVG(1.0 * temp) OVER (PARTITION BY city ORDER BY day ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING)! We filtered out partial windows and ranked peak heat waves with ROW_NUMBER().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*94XCqqnhQ8WbcLKIxMsKaA.png" /></figure><figure><img alt="VS Code SQL query and result table showing warmest 7-day windows for Beijing, Brasilia, Cape Town, Delhi, London, and Moscow." src="https://cdn-images-1.medium.com/max/975/1*DbUQKfOktdGNkxSaJ964aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FxPt_RE-o9UCKpjNAGce9w.png" /><figcaption><em>Figure 15: SQL Task 4 (s04) finding peak 7-day warming streaks across 6 global capital cities in VS Code.</em></figcaption></figure><p><strong>The SQL Autograder Scorecard: 4 / 4 Tasks Passed (100%)</strong></p><p>When we executed p.score(), the cohort database autograder verified our query cryptographic signatures and awarded a perfect 100% pass mark across all four data engineering challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*faPEVbrgp_y9zdARq5wYWg.png" /></figure><figure><img alt="VS Code terminal output showing Practice Score: 4 / 4 tasks passed with all green PASS confirmations." src="https://cdn-images-1.medium.com/max/975/1*KEFQO68hs_ncRJTwk-UdqA.png" /><figcaption><em>Figure 16: Automated SQL practice grading suite confirming 4 / 4 tasks passed in VS Code.</em></figcaption></figure><p><strong>8. Lessons Learned: Stumbling Into Potholes and Bouncing Back</strong></p><p>Let us be real with each other: nobody becomes confident in tech without stumbling into a few potholes along the way! Here are the real challenges we faced this week, and how we tackled them together:</p><p>· <strong>• The Off-by-One Sliding Window Trap: </strong>When writing Problem 1 (max_window_sum), our first attempt had an off-by-one boundary error where we missed the final day of the array. We fixed this by sketching the indices on paper and using range(k, len(nums)). Visualizing pointers with a pen and notepad is a superpower.</p><p>· <strong>• The Nested Window Function Shock: </strong>In SQL Task 3, we initially tried writing LAG(SUM(…) OVER (…)) directly. SQL Server immediately barked at us: ‘Windowed functions cannot be used in the context of another windowed function!’ We took a sip of water, stepped back, and split the query into two clean Common Table Expressions (CTEs): one to compute the running total, and a second to apply the LAG() subtraction. That solved it instantly.</p><p>· <strong>• The Table Name Detective Work: </strong>When querying city weather tables, we initially looked for week06.beijing_2014, but the database returned an error that the table did not exist. By inspecting the cohort schema, we discovered the tables had airport code suffixes (e.g. beijing_pek_2014, moscow_svo_2014). Never guess table names — always verify with metadata queries.</p><p><strong>9. Let Us Connect: Our Community Challenge For You!</strong></p><p>If you have read all the way to this point with us, give yourself a big round of applause! You have officially demystified Data Structures, Algorithms, and SQL without shedding tears, and you can now walk into any technical room with your head held high.</p><p>Now, before you go, we want to hear your voice! We have a fun community question for you to answer in the comments below:</p><p><strong>COMMUNITY CHALLENGE OF THE WEEK<br> </strong><em>Imagine you are building a real-time leaderboard for a mobile fintech app in Nigeria that processes millions of transactions daily. You want to display the Top 10 highest spenders of the day in real time. Would you sort the entire database every 5 minutes (O(N log N)), or would you use a Min-Heap of size 10 (O(N log 10))? Tell us in the comments what approach you would choose and why.</em></p><p>Drop your thoughts in the comment section below, let us debate and learn together! If this article made Big-O and DSA click for you, do not forget to hit that applause button (give it up to 50 claps!) and share it with a friend who is currently wrestling with coding concepts. Until our next project, keep coding with joy.</p><p>Engr. Raji Faruq Ishola cares.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4410d153c126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Morning Tea to Millions of Dollars: How I Decoded Global Trade Using Python and SQL]]></title>
            <link>https://medium.com/@faruqraji604/from-morning-tea-to-millions-of-dollars-how-i-decoded-global-trade-using-python-and-sql-abc7cd961a88?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc7cd961a88</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 01:27:15 GMT</pubDate>
            <atom:updated>2026-10-28T01:30:11.035Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner’s heartfelt journey into the world of Data Science , how everyday curiosity turns into multi-million dollar discoveries.</em></p><h3><strong>H</strong>ave you ever poured a splash of milk into your morning tea or coffee and wondered: *Where did this actually come from?</h3><p>Before I started learning data science, milk was just something I grabbed from the grocery fridge without a second thought. But this week, looking at millions of rows of real-world United Nations trade data, my perspective completely transformed.</p><p>Behind that carton of milk sits a massive, interconnected global web of dairy farmers, cargo freighters, refrigerated containers, and international trade contracts worth hundreds of millions of dollars.</p><p>In Week 8 of my Data Analytics journey with<strong> Dataraflow</strong>, I set out to answer big economic questions using two of the most essential tools in modern tech: <strong>Python</strong> and <strong>SQL</strong>. If you are someone who thinks data science is only for math geniuses or seasoned software engineers, let me tell you my story. If I can do this, <strong>you can too</strong>.</p><p>Here is what I built, the surprises I uncovered, the obstacles I overcame, and how I earned a 100% score on my technical assessment.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>The Mission: Unpacking the UK’s Dairy Secrets</strong></p><p>Our project focused on the United Kingdom’s trade in milk and cream products. In the international trade register, commodities are tracked by standardized Harmonized System (HS) codes:</p><ul><li>‘0401’: Fresh milk and cream (neither concentrated nor containing added sugar).</li><li>‘0402&#39;: Processed milk (concentrated, powdered, or sweetened milk products).</li></ul><p>Working with our cohort database, I had access to real UN Comtrade records spanning the first five months of 2015. My objective was to answer four critical questions:</p><ul><li>1. Does the UK export more milk than it imports (trade surplus), or is it losing money (trade deficit)?</li><li>2. Who are the UK’s biggest trading allies on the global stage?</li><li>3. Who are the faithful, recurring buyers that purchase UK milk every single month?</li><li>4. Which countries maintain two-way trade, both buying from and selling to the UK?</li></ul><p>_________________________________________________________________</p><h3>Step 1: Taming Messy Data &amp; The “World” Trap</h3><p>The first lesson you learn in data analytics is that raw data is rarely ready for decision-makers right away.</p><p>When I initially queried the database table using Python’s `pandas` library, the dataset contained raw numeric codes instead of human-readable categories. A business stakeholder doesn’t want to decipher 0401, they want to see ”unprocessed milk”.</p><p>I wrote a clean helper function to translate these codes into intuitive categories. But right after, I encountered a classic trap that catches many beginners: the aggregate row labeled `World`.</p><p>In trade registries, records exist for individual sovereign nations (like France, Germany, or Ireland), but the dataset also contains a summary row labeled `”World”` representing the combined total of every country on Earth. If you don’t filter out ”World”`, every sum, average, and chart you create ends up doubled!</p><p>I filtered out the aggregate noise, selected our primary analytical dimensions, and prepared our clean dataset.</p><figure><img alt="Jupyter notebook cell showing Python code loading UK milk trade data from a SQL database, defining the milkType function to decode codes 0401 and 0402 into unprocessed and processed categories, and filtering out World aggregate rows." src="https://cdn-images-1.medium.com/max/797/1*T01wE0370LDdugql1fjyNQ.png" /><figcaption><em>Loading raw UN Comtrade records with Pandas, mapping technical HS codes into intuitive categories, and excluding aggregate ‘World’ rows to prevent double counting.</em></figcaption></figure><h3>Step 2: The Big Discovery — A $108 Million Trade Surplus!</h3><p>Once the data was verified and clean, it was time to calculate the score: <strong>Total Exports vs. Total Imports</strong>.</p><p>When I aggregated the trade flow in Python, the numbers were staggering:</p><ul><li>Total UK Dairy Exports: Over $265 Million USD</li><li>Total UK Dairy Imports: Around $156 Million USD</li></ul><p>Trade Surplus = Exports — Imports = +$108,545,683 USD</p><p>The United Kingdom was not merely trading milk; it maintained a positive trade balance exceeding $108 Million Dollars in just the first five months of the year! The UK dairy sector is an export powerhouse.</p><figure><img alt="Output table and printed summary showing total UK dairy exports of 265 million dollars, imports of 156 million dollars, and an overall positive trade balance surplus of 108.5 million dollars USD" src="https://cdn-images-1.medium.com/max/1024/1*KSlpG6jwgdCOXLs7Ub0W6w.png" /><figcaption><em>Figure 2: Aggregated UK dairy trade flows for Jan–May 2015, revealing over $265M in exports against $156M in imports, resulting in a positive trade surplus of $108.5M USD.</em></figcaption></figure><h3>Step 3: Meet the Best Friend — The Ireland Connection</h3><p>Next, I wanted to see where all this dairy volume was flowing. Who buys the most from the UK, and who supplies the UK when local stocks run low?</p><p>When I grouped the transactions by partner country, one nation stood out far above the rest: Ireland.</p><ul><li>Exports to Ireland: Over $128 Million USD (nearly half of all UK dairy exports!).</li><li>Imports from Ireland: Around $85 Million USD.</li></ul><p>Other prominent partners included the <strong>Netherlands, France, Germany, and China</strong>. What made this finding remarkable was the asymmetry: the UK ships significantly more dairy across the Irish Sea than it brings back. Furthermore, I discovered that 20 nations engage in two-way (bi-directional) dairy trade with the UK.</p><figure><img alt="Pandas DataFrame displaying top 10 UK export and import destinations, with Ireland leading at 128 million dollars in exports and 85 million dollars in imports, followed by the Netherlands, France, and Germany." src="https://cdn-images-1.medium.com/max/708/1*-O3UEeSWWxeRpDKD-9agOw.png" /><figcaption><em>Figure 3: Side-by-side comparison of the UK’s top export and import partners, demonstrating Ireland’s overwhelming lead alongside active bi-directional trade partners.</em></figcaption></figure><h3>Step 4: The “Golden 16” — The Reliable Customers</h3><p>In business and supply chain management, one-off spikes in sales are exciting, but consistent recurring customers are the true backbone of an economy.</p><p>Using custom group filtering (`.filter()`) in Pandas, I searched for countries that bought both fresh milk (`0401`) and powdered milk (`0402`) in every single month from January through May without interruption (yielding exactly 10 recorded transactions).</p><p>The result? Out of dozens of global destinations, exactly <strong>16 countries</strong> were reliable, loyal monthly buyers.</p><p>And here is the most powerful insight of the entire analysis: <strong>These 16 countries accounted for more than 75% of the UK’s entire dairy export revenue</strong>!</p><p>In business economics, this is a clear demonstration of the Pareto Principle (the 80/20 rule): a small, dependable core of loyal accounts drives three-quarters of the nation’s international revenue.</p><figure><img alt="Code output showing 16 regular partner countries identified with Pandas filter function, accounting for 75.8percent of the UK’s total dairy export revenue across the five-month period." src="https://cdn-images-1.medium.com/max/1024/1*5OoHSG4RatFqx2nH1t61Ug.png" /><figcaption><em>Figure 4: The ‘Golden 16’ — filtering for persistent monthly buyers that purchased milk goods every single month, generating 75.4% of all UK export revenue.</em></figcaption></figure><h3><strong>Step 5: Turning Numbers into Art with Seaborn</strong></h3><p>Tables of numbers tell what happened, but <strong>visualizations explain why it matters</strong>.</p><p>Using Python’s <strong>Seaborn</strong> and Matplotlib. <strong>libraries</strong>, I built a 6-panel statistical dashboard:</p><p>1. <strong>Log-Transformed Histogram</strong>: Trade values range from modest $500 shipments to $50 million bulk contracts. Taking the logarithm revealed that dairy transactions form an elegant bell curve centered between $10,000 and $100,000.<br>2. KDE Density Plot: Comparing export curves against import curves to visualize market value concentrations.<br>3.<strong> Violin Plo</strong>t: Contrasting unprocessed raw milk vs. processed milk powder.<br>4. <strong>Regression Plot:</strong> Plotting linear trendlines across calendar months to track market momentum.<br>5. <strong>Monthly Partner Heatmap</strong>: Using color intensity to instantly identify monthly transaction shifts across the top 10 partner nations.</p><figure><img alt="Six-panel data visualization dashboard showing a log-transformed histogram of trade values, KDE density plot comparing exports and imports, violin plot of milk commodity types, regression lines over time, and a monthly trade heatmap for top countries." src="https://cdn-images-1.medium.com/max/1024/1*HwpkoVbKzCfm9E0Im6karQ.png" /><figcaption><em>Figure 5: Statistical visualization dashboard created with Seaborn and Matplotlib, featuring log-scale histograms, KDE density comparisons, violin plots, regression trendlines, and partner trade heatmaps.</em></figcaption></figure><p><strong>Step 6: Conquering the SQL Autograder (100% Score!)</strong></p><p>While Python is fantastic for exploratory data science, modern data infrastructure runs on <strong>SQL</strong> inside relational enterprise databases.</p><p>Part C of our assignment challenged us with an automated grading suite featuring 5 complex SQL tasks:</p><ul><li>Task 1 (`s01`): Summarizing trade aggregates using `SUM`, `AVG`, and `COUNT`.</li><li>Task 2 (`s02`): Producing monthly totals and grand annual subtotals in a single query pass using `GROUPING SETS`.</li><li>Task 3 (`s03`): Calculating dynamic market share percentages using analytic window functions (`SUM() OVER ()`).</li><li>Task 4 (`s04`): Isolating the Top 3 partners per flow with window ranking (`DENSE_RANK()`) and `HAVING` filters.</li><li>Task 5 (`s05`): Structuring a tidy table for stacked bar charts, rolling small-volume countries into an `’Other’` category.</li></ul><p>When I ran the final scoring cell, every query matched its cryptographic fingerprint:</p><p>```text<br>========================================<br>Practice Score: 5 / 5 tasks passed!<br> s01 (SQL Task 1 · Quick milk aggregate): [PASS]<br> s02 (SQL Task 2 · Subtotals with GROUPING SETS): [PASS]<br> s03 (SQL Task 3 · Top 10 export partners): [PASS]<br> s04 (SQL Task 4 · Top 3 per flow (window ranking)): [PASS]<br> s05 (SQL Task 5 · A tidy table for a stacked bar chart): [PASS]<br>========================================<br>```</p><figure><img alt="Six-panel data visualization dashboard showing a log-transformed histogram of trade values, KDE density plot comparing exports and imports, violin plot of milk commodity types, regression lines over time, and a monthly trade heatmap for top countries." src="https://cdn-images-1.medium.com/max/569/1*L6acNV91Tjt4xxOZA8Kyfw.png" /><figcaption><em>Figure 5: Statistical visualization dashboard created with Seaborn and Matplotlib, featuring log-scale histograms, KDE density comparisons, violin plots, regression trendlines, and partner trade heatmaps.</em></figcaption></figure><h3><strong>Challenges I Faced &amp; The Lessons That Stuck</strong></h3><p>I believe in being honest: <strong>nobody writes flawless code on their first try</strong>. Here were the biggest hurdles I faced this week and how I overcame them:</p><p>1. <strong>The Kernel &amp; Library Mismatch (`ModuleNotFoundError`):</strong><br> At one point, my VS Code notebook threw a red error saying `pymssql` was missing. I realized my notebook was pointing to a newly created virtual environment (`da35`) instead of the system Python. Once I installed the required database connectors into that environment and refreshed the kernel, everything executed smoothly. <br> *Lesson:* Always check which kernel is active in the top-right corner of your IDE!</p><p>2. <strong>Understanding `WHERE` vs. `HAVING` in SQL:</strong><br> In SQL, filtering before grouping (`WHERE`) is fundamentally different from filtering after grouping (`HAVING`). Filtering countries with over $5 Million in trade required aggregating first with `SUM([Trade Value (US$)])` and then filtering with `HAVING`. Once you understand this order of operations, SQL becomes second nature.</p><h3><strong>Final Thoughts On Why You Should Start Today</strong></h3><p>If you are standing on the outside of the tech world wondering if you have what it takes: <strong>take the leap.</strong></p><p>Data analytics is not about memorizing complex formulas; it is about curiosity. It is about looking at something as everyday as a carton of milk and using code to unveil the hidden economic ties that connect our world.</p><p>Every error message is simply a clue waiting to be solved. And the feeling when that autograder turns green and outputs `5 / 5 tasks passed` is worth every bit of persistence.</p><p>Special thanks to my mentors at Dataraflow, to Aloh, and to everyone supporting me on this learning journey.</p><p>With an honest review though, did you find this breakdown helpful? Give it a clap, most loving kindly leave a comment with your thoughts, or share your own learning experiences below!</p><p><strong>#DataScience #Python #SQL #DataAnalytics #DataStorytelling #LearningInPublic #MediumWriters</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc7cd961a88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Real-World Data Cleaning, Merging & Analysis with Pandas and SQL: A Week 7 Deep Dive]]></title>
            <link>https://medium.com/@faruqraji604/mastering-real-world-data-cleaning-merging-analysis-with-pandas-and-sql-a-week-7-deep-dive-eefab725bfcd?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefab725bfcd</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 18:42:08 GMT</pubDate>
            <atom:updated>2026-10-18T18:42:08.633Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Faruq Raji</em><br> <em>Data Science Intern @ DataRaflow</em></p><h3>Data in textbooks is clean, well-formatted, and ready to feed directly into models. Data in the real world, however, is messy, inconsistent, filled with rogue whitespace, strange HTML artifacts, and spread across disparate database tables.</h3><p>This week in the DataRaflow internship programme, we tackled the foundational reality of data analytics: <strong>cleaning and visualising weather observations</strong>, <strong>transforming and combining World Bank socioeconomic datasets</strong>, and <strong>pushing heavy data transformation workloads directly into SQL</strong>.</p><p>Here is a full breakdown of the techniques, findings, challenges, and insights from this week’s projects.</p><p>_________________________________________________________________</p><h3>1. What I Learnt This Week</h3><p>Before jumping into analysis, data must undergo structural integrity checks. This week reinforced four core pillars:</p><h3>A. Data Munging &amp; Type Integrity</h3><ul><li><strong>Cleaning String Columns:</strong> Datasets often carry trailing artifacts. For instance, wind directions in our weather export came with trailing HTML breaks like &#39;180&lt;br /&gt;&#39;. Cleaning requires stripping whitespace with .str.strip(), replacing HTML substrings with .str.replace(&#39;&lt;br /&gt;&#39;, &#39;&#39;), and explicitly casting types with .astype(int).</li><li><strong>Datetime Slicing:</strong> Converting raw date strings into true datetime64 objects and setting them as the DataFrame index allows for intuitive, human-readable date slicing (e.g., df.loc[&#39;2014-06-01&#39;:&#39;2014-08-31&#39;]).</li></ul><h3>B. The Four Relational Joins</h3><p>Combining data from multiple sources requires selecting the right join strategy:</p><ol><li><strong>Inner Join:</strong> Retains only keys common to both datasets (intersection).</li><li><strong>Left Join:</strong> Retains all observations from the primary table, filling missing matches with NaN.</li><li><strong>Right Join:</strong> Retains all observations from the secondary table.</li><li><strong>Outer Join:</strong> Retains the union of all keys from both datasets.</li></ol><h3>C. Correlation vs. Causation &amp; Logarithmic Visualisation</h3><ul><li><strong>Spearman Rank Correlation:</strong> Unlike Pearson correlation (which evaluates purely linear relationships), Spearman evaluates monotonic relationships using ranks, making it much more robust against extreme outliers.</li><li><strong>Logarithmic Scales:</strong> Macroeconomic figures like GDP span orders of magnitude (from millions to trillions). Visualising this on a standard linear scale clumps 90% of data points onto the left axis. Logarithmic axes (logx=True / logy=True) reveal the underlying distribution.</li></ul><h3>D. Doing Heavy Lifting in SQL Before Pandas</h3><p>Real-world data pipelines rarely pull massive raw tables into memory just to clean them in Python. Writing queries using <strong>Common Table Expressions (CTEs)</strong>, TRY_CONVERT(), and <strong>window functions</strong> (SUM(...) OVER (ROWS BETWEEN ...)) allows us to prepare and aggregate data directly within SQL Server.</p><p>_________________________________________________________________________</p><h3>2. What I Solved &amp; Key Projects</h3><h3>Project A: Finding the Optimal Summer Holiday in London</h3><p>Planning a vacation around London’s notoriously unpredictable weather requires looking at historical patterns. Using historical weather data for London Heathrow (2014), the objective was to identify <strong>two ideal 7-day vacation periods</strong> in the summer (June, July, August) that maximized warmth while minimizing rain.</p><p><strong>Our Approach:</strong></p><ol><li>Loaded the dataset and cleaned all column headers and data types.</li><li>Filtered for summer months (2014-06-01 to 2014-08-31).</li><li>Computed 7-day rolling totals for precipitation and average maximum temperatures.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-FWbBLcFE1xRZZVNBXXmA.png" /><figcaption><em>London Summer 2014 daily temperature curves and precipitation bar chart.</em></figcaption></figure><p><strong>The Results:</strong> The 7-day rolling analysis identified two dry, warm windows:</p><ul><li><strong>Week 1 (June 23 to June 29, 2014):</strong> Total rainfall of <strong>0.0 mm</strong>, pleasant mean temperatures around 19.6∘C, and afternoon highs reaching 24.4∘C.</li><li><strong>Week 2 (July 20 to July 26, 2014):</strong> Total rainfall of <strong>0.0 mm</strong>, representing the peak of summer warmth with daily highs averaging 28.0∘C.</li></ul><p>__________________________________________________________________________</p><h3>Project B: GDP vs. Life Expectancy — The Power of Per Capita Metrics</h3><p>A common hypothesis in development economics is that richer nations enjoy longer lifespans due to better healthcare, workplace safety, and infrastructure. But how strong is this relationship in reality?</p><p>We merged two World Bank 2013 datasets: <strong>Gross Domestic Product (GDP in USD)</strong> and <strong>Life Expectancy at Birth</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*KinncTawPTBs3e4mGhy1Bw.png" /><figcaption><em>Comparing Inner, Left, Right, and Outer joins when merging World Bank datasets</em></figcaption></figure><h4>Key Findings &amp; Critical Discoveries:</h4><ol><li><strong>Top 10 Economies ≠ Top 10 Longevity:</strong><br> Comparing the 10 largest economies against the 10 countries with the highest life expectancy revealed only <strong>3 overlapping nations</strong>: <strong>France, Italy, and Japan</strong>. Massive economies like the US, China, and India did not rank in the global top 10 for longevity.</li><li><strong>The “Wealthy but Low Longevity” Outliers:</strong><br> Looking at the right half of our scatterplot (countries with higher total GDP), three countries stood out with life expectancies below 60 years: <strong>Nigeria (52 yrs)</strong>, <strong>South Africa (57 yrs)</strong>, and <strong>Angola (52 yrs)</strong>.<br> <em>Why?</em> Total GDP reflects economic size, but resource extraction (oil/mining) often concentrates wealth without translating into robust public healthcare, compounded by high burdens of infectious diseases (HIV/AIDS, malaria) and economic inequality.</li><li><strong>The Per Capita Transformation:</strong><br> When examining total aggregate GDP vs. Life Expectancy, the Spearman rank correlation was a modest <strong>0.500.500.50</strong>.<br> However, once we merged World Bank population data and computed <strong>GDP per Capita (GDP/Population)</strong>, the correlation jumped dramatically to <strong>0.75280.75280.7528</strong> (p=2.94×10^−35).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*udXKja7nJPGRsHNAqskK8A.png" /><figcaption>Strong positive correlation (r=0.75r = 0.75r=0.75) between GDP per Capita and Life Expectancy on a logarithmic scale.</figcaption></figure><blockquote>________________________________________________________________________</blockquote><h3>Project C: Does Country Population Correlate with Longevity?</h3><p>As part of the independent project assessment, I investigated whether a country’s population size itself correlates with life expectancy.</p><ul><li><strong>Hypothesis:</strong> Do smaller populations enjoy easier healthcare delivery, or do larger populations benefit from economies of scale?</li><li><strong>Finding:</strong> The Spearman rank correlation between Population and Life Expectancy was <strong>0.05190.05190.0519</strong> with a p-value of <strong>0.49500.49500.4950</strong>. Because p&gt;0.05p &gt; 0.05p&gt;0.05, there is <strong>no statistically significant relationship</strong> between population size and life expectancy. Micro-states (Luxembourg, Iceland) and large countries (Japan) both achieve long life expectancies.</li></ul><p>_________________________________________________________________________</p><h3>SQL Practice: Moving Logic into the Database</h3><p>In the final section of the take-home, we translated our data preparation workflows directly into SQL Server queries:</p><ul><li><strong>Task 1:</strong> Cleaned strings ending in &lt;br /&gt; using REPLACE() and filtered for northerly winds (&gt;350∘).</li><li><strong>Task 2:</strong> Cast dates using TRY_CONVERT(date, GMT) and queried a specific date range.</li><li><strong>Task 3:</strong> Joined GDP and Life Expectancy tables to retrieve the top 10 countries under $10B\$10\text{B}$10B GDP sorted by longevity.</li><li><strong>Task 4:</strong> Used a LEFT JOIN to identify exactly <strong>29 rows lost</strong> due to missing values.</li><li><strong>Task 5:</strong> Engineered a 7-day rolling precipitation window using SQL window functions:</li></ul><pre>SUM(Precipitationmm) OVER (<br> ORDER BY [day] ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING<br>)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*phIb7bBMNnQwN_PyQw-eDw.png" /><figcaption><em>100% autograder pass across all 5 SQL practice tasks</em></figcaption></figure><p>________________________________________________________________________</p><h3>3. Challenges Faced &amp; How I Overcame Them</h3><ol><li><strong>Hidden Whitespace &amp; KeyErrors:</strong><br> <em>The Challenge:</em> Selecting &#39;Mean Humidity&#39; initially threw a KeyError.<br> <em>How I Solved It:</em> The CSV column actually had a leading space (&#39; Mean Humidity&#39;). I used df.columns = df.columns.str.strip() across the entire DataFrame as an automatic standard cleaning step.</li><li><strong>Skewed Scatterplots:</strong><br> <em>The Challenge:</em> Initially, scatterplots of GDP had all data points crowded in a dense strip against the left axis, making analysis impossible.<br> <em>How I Solved It:</em> Applied logx=True, switching to an exponential scale (10^2, 10^3, 10^4…), which unfolded the spread and made trends instantly readable.</li><li><strong>Window Frame Boundary Edge-Cases in SQL:</strong><br> <em>The Challenge:</em> In SQL Task 5, finding the driest 7-day window inside summer using ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING caused days at the end of August to count truncated windows of fewer than 7 days.<br> <em>How I Solved It:</em> Added COUNT(*) OVER (...) in the CTE and filtered for WHERE win_count = 7, guaranteeing only true 7-day windows were considered.</li></ol><p>_____________________________________________________________________________</p><h3>4. Key Takeaways &amp; Advice for Others</h3><ul><li><strong>Always Inspect Before You Query:</strong> Check .dtypes and strip whitespace immediately after loading data.</li><li><strong>Aggregates Can Deceive:</strong> Total national GDP is an inadequate measure of human welfare; always consider per-capita metrics when analyzing quality of life.</li><li><strong>Harness SQL for What It Does Best:</strong> Clean and aggregate in the database first, so pandas receives lean, structured tables.</li></ul><p><em>Feel free to connect or share your thoughts in the comments below please. Thank You!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefab725bfcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATARAFLOW WEEK6 LIKE *DATARAWOLF*; A GREATEST SKILL WON WITH HONEST TOIL.]]></title>
            <link>https://medium.com/@faruqraji604/dataraflow-week6-like-datarawolf-a-greatest-skill-won-with-honest-toil-16982678b4f3?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16982678b4f3</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 16:03:48 GMT</pubDate>
            <atom:updated>2026-10-16T16:03:48.805Z</atom:updated>
            <content:encoded><![CDATA[<p>Navigating the Cloud &amp; Conquering Intermediate SQL: My Week 6 Data Assessment Journey</p><p>Data analysis is rarely just about writing a clean query. More often than not, it is a combination of mastering complex logic, like conditional aggregations, multi-table joins, and window functions , while successfully troubleshooting environment configuration and cloud security hurdles.</p><p>This week, I tackled an intensive <strong>Intermediate SQL Assessment</strong> featuring 10 rigorous tasks. In this article, I’ll walk through what I learned, the specific problems I solved using real code examples, the roadblocks I encountered, and how I overcame them.</p><h3>1. What I Learned: Core Concepts &amp; Techniques</h3><p>Moving past basic `SELECT` statements required mastering several advanced SQL patterns:<br><strong>Conditional Aggregation:</strong> Using `SUM(CASE WHEN … THEN 1 ELSE 0 END)` to calculate metrics like specific churn rates or multi-condition counts in a single pass.<br><strong>Filtering Groups with `HAVING`:</strong> Moving beyond row-level filters (`WHERE`) to filter aggregated subsets, such as verifying active participation across all 12 months of a year (`HAVING COUNT(DISTINCT Period) = 12`).<br><strong>Advanced Window Functions &amp; CTEs</strong>: Leveraging `ROW_NUMBER() OVER (PARTITION BY … ORDER BY …)` and sliding window frames (`ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`) to isolate top-tier records and calculate running totals.<br><strong>Environment Architecture:</strong> Structuring local Jupyter notebook environments in VS Code using Miniconda while connecting securely to remote Azure-hosted SQL databases.</p><h3>2. What I Solved: Code in Action</h3><p>To bring these concepts to life, here are three key patterns I implemented during the assessment:</p><p><strong>A. Conditional Aggregation &amp; Percentage Calculation (Task 3)</strong><br>To analyze customer churn by contract type, I combined conditional summing with division and rounding:<br>```sql<br>SELECT <br> Contract_Type,<br> COUNT(*) AS customers,<br> SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) AS churned,<br> ROUND(100.0 * SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) / COUNT(*), 1) AS churn_rate_pct<br>FROM customer_churn_prediction<br>GROUP BY Contract_Type<br>ORDER BY churn_rate_pct DESC;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7uiyxErhoYBFywKvCTzEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vow77GOJJ72QQS0kSTULOg.png" /></figure><h3>B. Group Filtering with HAVING (Task 4)</h3><p>When identifying global trade partners that maintained continuous milk exports in all 12 months, standard WHERE clauses aren&#39;t enough because they filter before grouping. HAVING handles the aggregated count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caWtqOsMDwqbWtDthOno_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*0t6ZmkTiQGh9MwWRrnQBNg.png" /></figure><h3>C. Ranking with CTEs and Window Functions (Task 8)</h3><p>To find the top 3 highest-value transactions per customer, wrapping a ROW_NUMBER() function inside a Common Table Expression (CTE) made the filtering clean and readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekrB6PzsX2ed03dTAt8GgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqAiRw0XtCWs0hZV-_Aotg.png" /></figure><h3>3. Challenges I Faced</h3><p>While writing the SQL was rewarding, the infrastructure brought unique hurdles:</p><ul><li><strong>The Missing </strong><strong>db Module:</strong> When opening the assignment repository, the workspace initially lacked the local helper structure (db/dataraflow_db.py and __init__.py) required to import connection utilities into the notebook.</li><li><strong>Dynamic IP Firewall Blocks:</strong> Because the cohort database is hosted securely on Azure, switching networks or letting the IP address refresh instantly triggered firewall security exceptions (40615: Client with IP address ... is not allowed to access the server).</li></ul><h3>4. How I Overcame Them</h3><ul><li><strong>Structuring the Local Package:</strong> I resolved the import errors by manually creating the project root’s db folder, inserting the correct dataraflow_db.py connection code, and adding an __init__.py module indicator so Python&#39;s path-search loop could successfully resolve dependencies.</li><li><strong>Bypassing Network Restrictions:</strong> I navigated the dynamic IP blocks by regularly whitelisting my active local network address via the course portal dashboard and utilizing kernel restarts to clear module caches.</li></ul><h3>5. Final Insights &amp; Advice for Learners</h3><p>If you are diving into intermediate SQL and cloud-connected notebooks, my biggest pieces of advice are:</p><ol><li><strong>Master the Error Messages:</strong> Azure firewall errors and Python ModuleNotFoundError prompts look intimidating, but they give you exact clues—whether it&#39;s a missing .py extension or an un-whitelisted IP.</li><li><strong>Build Queries Incrementally:</strong> When tackling window functions or conditional aggregates, build them from the inside out (starting with your base table, adding your GROUP BY, and layering on window clauses last)…</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16982678b4f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATARAFLOW WEEK6 LIKE *DATARAWOLF*; A GREATEST SKILL WON WITH HONEST TOIL.]]></title>
            <link>https://medium.com/@faruqraji604/dataraflow-week6-like-datarawolf-a-greatest-skill-won-with-honest-toil-4f2717c66f99?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f2717c66f99</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 15:54:29 GMT</pubDate>
            <atom:updated>2026-10-16T15:54:29.075Z</atom:updated>
            <content:encoded><![CDATA[<p>Navigating the Cloud &amp; Conquering Intermediate SQL: My Week 6 Data Assessment Journey</p><p>Data analysis is rarely just about writing a clean query. More often than not, it is a combination of mastering complex logic, like conditional aggregations, multi-table joins, and window functions , while successfully troubleshooting environment configuration and cloud security hurdles.</p><p>This week, I tackled an intensive <strong>Intermediate SQL Assessment</strong> featuring 10 rigorous tasks. In this article, I’ll walk through what I learned, the specific problems I solved using real code examples, the roadblocks I encountered, and how I overcame them.</p><h3>1. What I Learned: Core Concepts &amp; Techniques</h3><p>Moving past basic `SELECT` statements required mastering several advanced SQL patterns:<br><strong>Conditional Aggregation:</strong> Using `SUM(CASE WHEN … THEN 1 ELSE 0 END)` to calculate metrics like specific churn rates or multi-condition counts in a single pass.<br><strong>Filtering Groups with `HAVING`:</strong> Moving beyond row-level filters (`WHERE`) to filter aggregated subsets, such as verifying active participation across all 12 months of a year (`HAVING COUNT(DISTINCT Period) = 12`).<br><strong>Advanced Window Functions &amp; CTEs</strong>: Leveraging `ROW_NUMBER() OVER (PARTITION BY … ORDER BY …)` and sliding window frames (`ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`) to isolate top-tier records and calculate running totals.<br><strong>Environment Architecture:</strong> Structuring local Jupyter notebook environments in VS Code using Miniconda while connecting securely to remote Azure-hosted SQL databases.</p><h3>2. What I Solved: Code in Action</h3><p>To bring these concepts to life, here are three key patterns I implemented during the assessment:</p><p><strong>A. Conditional Aggregation &amp; Percentage Calculation (Task 3)</strong><br>To analyze customer churn by contract type, I combined conditional summing with division and rounding:<br>```sql<br>SELECT <br> Contract_Type,<br> COUNT(*) AS customers,<br> SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) AS churned,<br> ROUND(100.0 * SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) / COUNT(*), 1) AS churn_rate_pct<br>FROM customer_churn_prediction<br>GROUP BY Contract_Type<br>ORDER BY churn_rate_pct DESC;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7uiyxErhoYBFywKvCTzEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vow77GOJJ72QQS0kSTULOg.png" /></figure><h3>B. Group Filtering with HAVING (Task 4)</h3><p>When identifying global trade partners that maintained continuous milk exports in all 12 months, standard WHERE clauses aren&#39;t enough because they filter before grouping. HAVING handles the aggregated count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caWtqOsMDwqbWtDthOno_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*0t6ZmkTiQGh9MwWRrnQBNg.png" /></figure><h3>C. Ranking with CTEs and Window Functions (Task 8)</h3><p>To find the top 3 highest-value transactions per customer, wrapping a ROW_NUMBER() function inside a Common Table Expression (CTE) made the filtering clean and readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekrB6PzsX2ed03dTAt8GgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqAiRw0XtCWs0hZV-_Aotg.png" /></figure><h3>3. Challenges I Faced</h3><p>While writing the SQL was rewarding, the infrastructure brought unique hurdles:</p><ul><li><strong>The Missing </strong><strong>db Module:</strong> When opening the assignment repository, the workspace initially lacked the local helper structure (db/dataraflow_db.py and __init__.py) required to import connection utilities into the notebook.</li><li><strong>Dynamic IP Firewall Blocks:</strong> Because the cohort database is hosted securely on Azure, switching networks or letting the IP address refresh instantly triggered firewall security exceptions (40615: Client with IP address ... is not allowed to access the server).</li></ul><h3>4. How I Overcame Them</h3><ul><li><strong>Structuring the Local Package:</strong> I resolved the import errors by manually creating the project root’s db folder, inserting the correct dataraflow_db.py connection code, and adding an __init__.py module indicator so Python&#39;s path-search loop could successfully resolve dependencies.</li><li><strong>Bypassing Network Restrictions:</strong> I navigated the dynamic IP blocks by regularly whitelisting my active local network address via the course portal dashboard and utilizing kernel restarts to clear module caches.</li></ul><h3>5. Final Insights &amp; Advice for Learners</h3><p>If you are diving into intermediate SQL and cloud-connected notebooks, my biggest pieces of advice are:</p><ol><li><strong>Master the Error Messages:</strong> Azure firewall errors and Python ModuleNotFoundError prompts look intimidating, but they give you exact clues—whether it&#39;s a missing .py extension or an un-whitelisted IP.</li><li><strong>Build Queries Incrementally:</strong> When tackling window functions or conditional aggregates, build them from the inside out (starting with your base table, adding your GROUP BY, and layering on window clauses last)…</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f2717c66f99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATARAFLOW WEEK6 LIKE *DATARAWOLF*; A GREATEST SKILL WON WITH HONEST TOIL.]]></title>
            <link>https://medium.com/@faruqraji604/dataraflow-week6-like-datarawolf-a-greatest-skill-won-with-honest-toil-f32fb3227b2c?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f32fb3227b2c</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 12:29:58 GMT</pubDate>
            <atom:updated>2026-10-16T15:37:09.945Z</atom:updated>
            <content:encoded><![CDATA[<p>Navigating the Cloud &amp; Conquering Intermediate SQL: My Week 6 Data Assessment Journey</p><p>Data analysis is rarely just about writing a clean query. More often than not, it is a combination of mastering complex logic, like conditional aggregations, multi-table joins, and window functions , while successfully troubleshooting environment configuration and cloud security hurdles.</p><p>This week, I tackled an intensive <strong>Intermediate SQL Assessment</strong> featuring 10 rigorous tasks. In this article, I’ll walk through what I learned, the specific problems I solved using real code examples, the roadblocks I encountered, and how I overcame them.</p><h3><strong>1. What I Learned: Core Concepts &amp; Techniques</strong></h3><p>Moving past basic `SELECT` statements required mastering several advanced SQL patterns:<br><strong>Conditional Aggregation:</strong> Using `SUM(CASE WHEN … THEN 1 ELSE 0 END)` to calculate metrics like specific churn rates or multi-condition counts in a single pass.<br><strong>Filtering Groups with `HAVING`:</strong> Moving beyond row-level filters (`WHERE`) to filter aggregated subsets, such as verifying active participation across all 12 months of a year (`HAVING COUNT(DISTINCT Period) = 12`).<br><strong>Advanced Window Functions &amp; CTEs</strong>: Leveraging `ROW_NUMBER() OVER (PARTITION BY … ORDER BY …)` and sliding window frames (`ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`) to isolate top-tier records and calculate running totals.<br><strong>Environment Architecture:</strong> Structuring local Jupyter notebook environments in VS Code using Miniconda while connecting securely to remote Azure-hosted SQL databases.</p><h3><strong>2. What I Solved: Code in Action</strong></h3><p>To bring these concepts to life, here are three key patterns I implemented during the assessment:</p><p><strong>A. Conditional Aggregation &amp; Percentage Calculation (Task 3)</strong><br>To analyze customer churn by contract type, I combined conditional summing with division and rounding:<br>```sql<br>SELECT <br> Contract_Type,<br> COUNT(*) AS customers,<br> SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) AS churned,<br> ROUND(100.0 * SUM(CASE WHEN Churn = 1 THEN 1 ELSE 0 END) / COUNT(*), 1) AS churn_rate_pct<br>FROM customer_churn_prediction<br>GROUP BY Contract_Type<br>ORDER BY churn_rate_pct DESC;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7uiyxErhoYBFywKvCTzEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vow77GOJJ72QQS0kSTULOg.png" /></figure><h3>B. Group Filtering with HAVING (Task 4)</h3><p>When identifying global trade partners that maintained continuous milk exports in all 12 months, standard WHERE clauses aren&#39;t enough because they filter before grouping. HAVING handles the aggregated count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caWtqOsMDwqbWtDthOno_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*0t6ZmkTiQGh9MwWRrnQBNg.png" /></figure><h3>C. Ranking with CTEs and Window Functions (Task 8)</h3><p>To find the top 3 highest-value transactions per customer, wrapping a ROW_NUMBER() function inside a Common Table Expression (CTE) made the filtering clean and readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekrB6PzsX2ed03dTAt8GgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqAiRw0XtCWs0hZV-_Aotg.png" /></figure><h3>3. Challenges I Faced</h3><p>While writing the SQL was rewarding, the infrastructure brought unique hurdles:</p><ul><li><strong>The Missing </strong><strong>db Module:</strong> When opening the assignment repository, the workspace initially lacked the local helper structure (db/dataraflow_db.py and __init__.py) required to import connection utilities into the notebook.</li><li><strong>Dynamic IP Firewall Blocks:</strong> Because the cohort database is hosted securely on Azure, switching networks or letting the IP address refresh instantly triggered firewall security exceptions (40615: Client with IP address ... is not allowed to access the server).</li></ul><h3>4. How I Overcame Them</h3><ul><li><strong>Structuring the Local Package:</strong> I resolved the import errors by manually creating the project root’s db folder, inserting the correct dataraflow_db.py connection code, and adding an __init__.py module indicator so Python&#39;s path-search loop could successfully resolve dependencies.</li><li><strong>Bypassing Network Restrictions:</strong> I navigated the dynamic IP blocks by regularly whitelisting my active local network address via the course portal dashboard and utilizing kernel restarts to clear module caches.</li></ul><h3>5. Final Insights &amp; Advice for Learners</h3><p>If you are diving into intermediate SQL and cloud-connected notebooks, my biggest pieces of advice are:</p><ol><li><strong>Master the Error Messages:</strong> Azure firewall errors and Python ModuleNotFoundError prompts look intimidating, but they give you exact clues—whether it&#39;s a missing .py extension or an un-whitelisted IP.</li><li><strong>Build Queries Incrementally:</strong> When tackling window functions or conditional aggregates, build them from the inside out (starting with your base table, adding your GROUP BY, and layering on window clauses last)…</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f32fb3227b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning-Driven Inflow Performance Relationships (IPR): Building a High-Accuracy XGBoost…]]></title>
            <link>https://medium.com/@faruqraji604/machine-learning-driven-inflow-performance-relationships-ipr-building-a-high-accuracy-xgboost-1613f8f307a4?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1613f8f307a4</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 09:22:33 GMT</pubDate>
            <atom:updated>2026-10-09T09:25:18.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning-Driven Inflow Performance Relationships (IPR): Building a High-Accuracy XGBoost Proxy Model for Multiphase Reservoirs</h3><h3>Machine Learning-Driven Inflow Performance Relationships (IPR): A Reproducible Gradient Boosting Pipeline for Multiphase Petroleum Reservoirs</h3><p>Faruq Raji Ishola<br>2026–10–09</p><h4>Abstract</h4><p>This project establishes a reproducible, data-driven machine learning framework to model and predict transient oil flow rates in multiphase petroleum reservoirs. Traditional IPR curves rely on empirical correlations that often fall short under complex fluid properties and transient operating conditions. By leveraging an optimized XGBoost Regressor trained on physics-informed synthetic production data (N=5,000), the framework achieves exceptional predictive accuracy (R²=0.9956), offering production engineers an instantaneous tool for real-time well optimization.</p><p>GitHub Repository: <a href="https://github.com/rajifaruq2021-hue/dataraflow-portfolio/tree/main/ipr-machine-learning-research">https://github.com/rajifaruq2021-hue/dataraflow-portfolio/tree/main/ipr-machine-learning-research</a></p><h4>Introduction</h4><p>In petroleum engineering, accurate estimation of well productivity is foundational to reservoir management, pressure-volume-temperature (PVT) analysis, and long-term economic optimization. Historically, production engineers have relied heavily on empirical correlations — most notably Vogel (1968) in his seminal paper “Inflow Performance Relationships for Solution-Gas Drive Wells”, to model the non-linear relationship between bottomhole flowing pressure (P_wf) and oil flow rate (q). Later foundational contributions by Standing (1973) and Fetkovich (1973) further standardized empirical multi-rate testing and pseudo-steady-state deliverability equations across diverse depletion mechanisms.</p><p>However, while these classical methods offer computational efficiency for steady-state conditions, they frequently break down under complex multiphase fluid dynamics, shifting relative permeability ratios, varying water cuts, and transient operating regimes. Subsurface systems are inherently non-linear, meaning traditional curve-fitting often introduces severe errors when applied to heterogeneous formations or unconventional operating pressures. As Mohaghegh (2017) highlights in Data-Driven Reservoir Modeling, modern subsurface data science offers a powerful paradigm shift by framing production forecasting as a high-dimensional machine learning problem capable of learning complex interactions directly from data. Furthermore, Al-Mudhafar (2017) demonstrated that optimized machine learning algorithms significantly outperform traditional curve-fitting during complex reservoir characterization and performance prediction, laying the groundwork for robust proxy modeling.</p><h4>Methodology and Data Simulation</h4><ul><li>To bridge the gap between theoretical petroleum mechanics and data-driven prediction, we implemented a rigorous, enterprise-grade machine learning pipeline structured into dedicated src/ and data/ directories. This ensures full reproducibility, clear separation of concerns, and alignment with modern software engineering standards.</li><li>Synthetic Data Simulation (src/generate_ipr_data.py): Because real-world field production data is frequently proprietary, sparse, or affected by severe telemetry gaps, we engineered a robust synthetic simulation pipeline generating 5,000 production samples. The simulation is governed by foundational reservoir physics, capturing key operating parameters including initial reservoir pressure (P_r), bottomhole flowing pressure (P_wf), water cut, gas-oil ratio (GOR), and near-wellbore skin factor.</li></ul><p>Feature Engineering and Preprocessing (src/preprocess_data.py): Raw production logs alone rarely capture the true underlying physics of fluid flow. This stage processes the simulated CSV data to engineer critical domain-specific features, most notably the pressure drawdown (ΔP=P_r-P_wf), which serves as the primary driving force for fluid movement. Furthermore, the pipeline utilizes StandardScaler to center and normalize feature distributions, ensuring optimal numerical stability and convergence speeds for gradient-boosting algorithms.</p><h4>Traditional Problem Solving vs. Machine Learning Intervention</h4><p>To understand why a data-driven approach is essential in modern field operations, let us evaluate a standard production engineering problem using Vogel’s classical IPR method and contrast it with our machine learning pipeline.</p><h4>Case Study: Traditional Calculation</h4><p>Consider a well with a reservoir pressure (P_r) of 4,000 &quot;psi” , a maximum absolute open flow potential (q_max) of 1,000&quot; stb/day” established from historical tests, and a target bottomhole flowing pressure (P_wf) of 2,000 &quot;psi” (Vogel, 1968). Applying Vogel’s dimensionless correlation:<br>q/q_max =1–0.2(P_wf/P_r )-0.8(P_wf/P_r )²</p><ol><li>Calculate the pressure ratio: P_wf/P_r =2000/4000=0.5.</li><li>2. Substitute into the equation: q/1000=1–0.2(0.5)-0.8(0.5)²=0.7.</li><li>Solve for oil flow rate (q): q=0.7×1000=700 &quot;stb/day” .</li></ol><h4>Critical Analysis and Limitations</h4><p>While Vogel’s manual calculation gives a clean 700 &quot;stb/day” , it carries severe blind spots. As discussed by Apaydin &amp; Ozkan (2020), single-point empirical curves fail when multiphase dynamics shift, such as rising water cuts or changing gas-oil ratios (GOR). Relying on static curves for field management leads to sub-optimal choke sizing and delayed interventions, resulting in hundreds of barrels of deferred daily production and significant revenue loss over a well’s lifecycle.</p><h4>The Machine Learning Proxy Solution</h4><p>To overcome these bottlenecks, our pipeline deploys an optimized XGBoost Regressor trained on the engineered feature set. As noted by Chen &amp; Datta (2019), tree-based gradient boosting models excel at proxy modeling in petroleum engineering by capturing non-linear interactions across large multi-variable parameter spaces. This aligns closely with recent findings by Gupta &amp; Datta-Gupta (2021), El-Sebakhy (2022), and Zhang &amp; Wang (2023), who demonstrated that ensemble tree structures deliver exceptional predictive accuracy (R²=0.9956, RMSE=93.95 &quot;stb/day” ) and instantaneous inference speeds, allowing asset teams to run real-time well optimization without computational lag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI9tBaZkNupMdkJRfXdUaA.png" /></figure><h4>Conclusion and Future Scope</h4><p>The integration of machine learning into petroleum engineering does not seek to discard foundational physics, but rather to scale and augment it. As demonstrated through our workflow, while classical methods like Vogel’s equation provide a reliable first-order baseline, they fall short under transient multi-variable reservoir conditions. By deploying an optimized XGBoost Regressor (R²=0.9956, RMSE=93.95 &quot;stb/day” ), we have established a high-fidelity proxy model capable of real-time, accurate well performance prediction. This bridges the gap between theoretical reservoir mechanics and modern data science, unlocking faster, data-driven field decisions.<br>As this project scales into subsequent phases of the fellowship, future enhancements will include:</p><ul><li>Deep Learning Integration: Exploring Long Short-Term Memory (LSTM) neural networks to handle time-series production data and multi-well history matching.</li><li>Web Application Deployment: Packaging the trained model into an interactive web interface using Streamlit so field engineers can run live IPR simulations on the fly.</li><li>Field Data Calibration: Testing the architecture on real-world publicly available field benchmark datasets to further validate generalization.</li></ul><p>99 Vogel, J. V. (1968). Inflow Performance Relationships for Solution-Gas Drive Wells. Journal of Petroleum Technology, 20(01), 83–92. Fetkovich, M. J. (1973). The Isochronal Testing of Oil Wells. Society of Petroleum Engineers. Standing, M. B. (1973). Concerning the Calculation of Inflow Performance Relationships of Oil Wells. Journal of Petroleum Technology, 25(09), 1141–1142. Mohaghegh, S. D. (2017). Data-Driven Reservoir Modeling: Applications of Artificial Intelligence and Machine Learning in the Oil and Gas Industry. SPE Textbook Series. Al-Mudhafar, W. J. (2017). Optimized Machine Learning Algorithms for Reservoir Characterization and Performance Prediction. SPE Western Regional Meeting, SPE-185695-MS. Chen, Y., &amp; Datta, G. (2019). Application of Gradient Boosting Regression Trees (XGBoost) in Petroleum Engineering: A Review of Proxy Modeling. Computers &amp; Geosciences, 128, 10–22. Apaydin, O. G., &amp; Ozkan, E. (2020). Artificial Intelligence and Machine Learning in Petroleum Engineering: Recent Progress and Future Outlook. Journal of Petroleum Science and Engineering, 185, 106621. Gupta, A., &amp; Datta-Gupta, A. (2021). Fast Reservoir Proxy Modeling Using Machine Learning and Deep Neural Networks. SPE Reservoir Evaluation &amp; Engineering, 24(02), 410–425. El-Sebakhy, E. A. (2022). Advanced Computational Intelligence Techniques for Predicting Inflow Performance Relationships in Multiphase Reservoirs. Journal of Petroleum Exploration and Production Technology, 12(4), 981–997. Zhang, H., &amp; Wang, J. (2023). Comparative Analysis of Tree-Based Ensembles and Deep Neural Networks for Well Productivity Index Estimation. Petroleum Science, 20(3), 1540–1555.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1613f8f307a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let My Python Coding Do The Talking Volume 3.0 !!!]]></title>
            <link>https://medium.com/@faruqraji604/let-my-python-coding-do-the-talking-volume-3-0-b31f9e509dda?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31f9e509dda</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 23:41:50 GMT</pubDate>
            <atom:updated>2026-09-25T23:41:50.184Z</atom:updated>
            <content:encoded><![CDATA[<p>My Beginner-Friendly Guide to Week 3 Python: Step-by-Step Hands-On Practice</p><p>Raji Faruq Ishola</p><h3>Introduction</h3><p>Hello everyone. If you are completely new to tech and feel like coding is a closed door, I want to welcome you. When I started learning Python, everything looked like confusing jargon. That is why I created this simple, step-by-step guide for Week 3 of my DataraFlow journey. We will break down each core concept using everyday analogies, look at the clean code solutions, and include placeholders where you can look at the exercise screenshots and drop in your own screenshots to follow along</p><p>While I have written this explanation as simply as possible, as if I am explaining it to a complete beginner with zero tech background, so that anyone can follow along with how I solved these tasks, assignments, and assessments, I will also love you reading it to the very last where I have compressed the most helpful resources that you can also lay your hand on.</p><p>Take a cup of coffee and lets explore the world programming together.</p><h3>1. Modules &amp; Dates: Bringing in Extra Toolkits</h3><p>When my code started getting bigger, I learned about Modules. Think of a module as a pre-written code library or a specialized toolkit that you can open whenever you need extra help.</p><ul><li><strong>What is a module?</strong> A file containing a set of functions you want to include in your application. You bring it in using the import keyword.</li><li><strong>Working with Dates:</strong> Python doesn’t treat dates as a basic primitive data type, so we import the datetime module to work with date objects.</li></ul><h3>Hands-on Exercise Example: Current Date and Time</h3><p><strong>The Question:</strong> Write a program that prints the current date and time using the datetime module.<br> <strong>The Code Solution:</strong></p><p># I import the datetime module to work with dates<br> import datetime<br> <br> # I use now() to capture the exact current timestamp<br> x = datetime.datetime.now()<br> print(x)</p><p><strong>Beginner Explanation:</strong> When I run datetime.datetime.now(), Python pulls the current year, month, day, hour, minute, second, and microsecond straight from my system clock.</p><h3>2. Math Operations: Expanding Beyond Basics</h3><p>While Python handles basic arithmetic easily, it also includes a dedicated math module that extends our math capabilities.</p><ul><li><strong>Built-in Functions vs. Math Module:</strong> We have simple built-in functions like min(), max(), abs(), and pow(x, y)[cite: 11]. But for advanced things like square roots or factorials, we must import math.</li></ul><h3>Hands-on Exercise Example: Square Root Calculation</h3><p><strong>The Question:</strong> Import the math module and calculate the square root of 144.<br> <strong>The Code Solution:</strong></p><p># I import the math module to unlock advanced math functions<br> import math<br> <br> # I use math.sqrt() to find the square root<br> x = math.sqrt(144)<br> print(x) # Returns 12.0</p><p><strong>Beginner Explanation:</strong> Think of import math like opening a drawer full of specialized scientific tools. Once open, I can use math.sqrt() to calculate square roots instantly.</p><h3>3. Working with JSON: Universal Data Translation</h3><p>Modern applications often need to exchange data across different systems. That is where JSON (JavaScript Object Notation) comes in as a standard text format.</p><ul><li><strong>Parsing JSON (json.loads):</strong> If I receive a JSON text string from the internet, I use json.loads() to parse it into a standard Python dictionary.</li><li><strong>Converting to JSON (json.dumps):</strong> If I have a Python dictionary or list, I use json.dumps() to convert it into a JSON text string.</li></ul><h3>Hands-on Exercise Example: Dictionary to JSON</h3><p><strong>The Question:</strong> Convert a Python dictionary into a JSON string using the json module.<br> <strong>The Code Solution:</strong></p><p>import json<br> <br> # I create a simple Python dictionary<br> x = {“name”: “John”, “age”: 30, “city”: “New York”}<br> <br> # I convert the dictionary into a JSON string<br> y = json.dumps(x, indent=4)<br> print(y)</p><p><strong>Beginner Explanation:</strong> Python dictionaries are native to Python, but JSON formatting wraps them in text strings so other programs and websites can read them. Using indent=4 makes the output neat and readable for humans.</p><h3>4. PIP, Error Handling, User Input &amp; Virtual Environments</h3><p>When building software, we need to handle user mistakes safely, install external packages, and keep our projects organized.</p><ul><li><strong>Error Handling (try/except):</strong> The try block lets us test code for errors, while the except block catches errors so our program doesn’t crash.</li><li><strong>PIP &amp; Virtual Environments:</strong> PIP is Python’s package manager used to download libraries. A virtual environment (venv) creates an isolated folder container for a project so packages don’t conflict with other apps on your computer.</li></ul><h3>Hands-on Exercise Example: Division by Zero Error Handling</h3><p><strong>The Question:</strong> Demonstrate a simple try/except block that handles division by zero.<br> <strong>The Code Solution:</strong></p><p>try:<br> # I test a risky operation that causes a math error<br> result = 10 / 0<br> except ZeroDivisionError:<br> # I catch the error gracefully with a friendly message<br> print(“Oops! You cannot divide a number by zero.”)</p><p><strong>Beginner Explanation:</strong> Normally, dividing by zero causes Python to panic and crash the entire application. Wrapping it in a try/except block acts like a safety guardrail: if an error happens, the program catches it and runs the backup message instead</p><h3>5. Reading and Writing Files</h3><p>File handling allows our programs to save data permanently onto our hard drive rather than losing it when the program closes.</p><ul><li><strong>The open() function:</strong> Takes a filename and a mode (like “r” for reading, “w” for writing, or “a” for appending).</li><li><strong>The with statement:</strong> Recommended because it automatically ensures files are properly closed after use, even if errors occur.</li></ul><h3>Hands-on Exercise Example: Writing and Reading JSON Files</h3><p><strong>The Question:</strong> Write a program that stores a list of student records into a JSON file, and then reads the file back into a Python object.<br> <strong>The Code Solution:</strong></p><p>import json<br> <br> students = [<br> {“name”: “Alice”, “age”: 20},<br> {“name”: “Bob”, “age”: 22}<br> ]<br> <br> # 1. Writing data to a file using mode ‘w’<br> with open(“students.json”, “w”) as f:<br> json.dump(students, f, indent=4)<br> <br> # 2. Reading data back from the file using mode ‘r’<br> with open(“students.json”, “r”) as f:<br> loaded_data = json.load(f)<br> <br> print(loaded_data)</p><p><strong>Beginner Explanation:</strong> I open a file in write mode (“w”) to dump my student list into permanent storage, and later open it in read mode (“r”) to bring the exact same data back into my Python script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*xhQwXf1-3QS0qk1p6HR6Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*XBarPUeTkzbTpnHJvnQxNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*CYcDkktaCY668SPe14r9uQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*DaOvzFbHqObWfvQUN2d9sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*9FV2-6Amz5JPFOq_ihKH1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*K9BiWm2VSJBYIxiISopO0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*iuIIbztx2GXKbfVnOfRKKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*O2EZgpYGuk0SwDZ1MECuvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*5v_GE4_rYyPXt6WVq0PHAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*dt9smfH7zYGYHcj_CapZ6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*t4JZyal2hAyDMfoSMmtgIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*76A-I1gs4P1I8gu0GiAuNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*Vat4NbIiu4xLxqYkbTJO6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*F-SfhevqmX0jqDVwToegSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*HnbFVIUSdlMcIRA_5847xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*oU6uHzfqI6QercO9dtwvcA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31f9e509dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Advanced Python — Object-Oriented Programming, Polymorphism, and Beyond.]]></title>
            <link>https://medium.com/@faruqraji604/mastering-advanced-python-object-oriented-programming-polymorphism-and-beyond-9f699b43ce34?source=rss-deb25eb8df4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f699b43ce34</guid>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Faruqraji]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 08:15:00 GMT</pubDate>
            <atom:updated>2026-09-15T16:01:16.222Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Advanced Python — Object-Oriented Programming, Polymorphism, and Beyond. With Live Code and Explanatory Output.</strong></h3><h3><strong>My DataraFlow Cohort 2 Journey</strong></h3><p><strong>The Python Developer’s Toolkit: OOP, Iterators, Polymorphism, and Scope <br></strong>Raji Faruq Ishola<br>2026–09–15</p><p>Hello, my wonderful network and fellow tech explorers! 🤗</p><p>As part of my incredible learning adventure in the DataraFlow Cohort 2 program, I am thrilled to share my complete walkthrough, practical code solutions, and deep insights from our Week 2 Take-Home assignments. This journey has not only sharpened my engineering skills but has also taught me how to write cleaner, more reusable, and production-ready code. My goal in sharing this comprehensive breakdown is to help anyone navigating object-oriented programming, iterators, polymorphism, and scope to gain valuable clarity and hands-on guidance! 🗺️✨</p><h3><strong>Course 1: Object-Oriented Programming (OOP) 🍪</strong></h3><p>Object-Oriented Programming is like designing blueprints for a manufacturing factory. A Class serves as our master template or cookie cutter, while an Object represents the individual products we bake and customize from that blueprint.</p><p><strong>Task 1: Constructor and String Formatting</strong></p><p><strong>Task: </strong>Insert the missing parts to make the code return John (36) using a constructor and string formatting.</p><p>class Person:<br> # This initializes our object with unique attributes when instantiated<br> def __init__(self, name, age):<br> self.name = name<br> self.age = age</p><p># This defines how our object is represented as a text string<br> def __str__(self):<br> return f”{self.name} ({self.age})”</p><p># Instantiate our object with custom data<br>p1 = Person(“John”, 36)</p><p># Print the object instance, triggering our __str__ method automatically<br>print(p1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEvBoSsI5nwI6gWLFbRPYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni4ibYfkr4TRZutQwpXi0A.png" /></figure><p><strong>Detailed Explanation and Commentary: This demonstrates how we define</strong> initialization logic using the __init__ constructor and format object outputs using the special __str__ method. When we pass “John” and 36 into Person(“John”, 36), Python binds those values to our object instance via self, allowing our f-string to return John (36) cleanly when printed.</p><p><strong>Task 2: Classes, Objects, and Properties</strong></p><p><strong>Task: </strong>Create a class named MyClass, instantiate an object called p1, and use it to print the value of x.</p><p>class MyClass:<br> # Define a class property<br> x = 5</p><p># Instantiate our object<br>p1 = MyClass()</p><p># Access and print the property using our object instance<br>print(p1.x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXRiWjYcHjP8P_ztV9Os5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*bIcxTaZukp2b48PGhHZugg.png" /></figure><p><strong>Detailed Explanation and Commentary: This illustrates how an object</strong> accesses variables stored inside its parent class blueprint. By writing p1 = MyClass(), we bring the template to life, and p1.x reaches inside to fetch the stored value 5.</p><h3><strong>Course 2: Inheritance 🧬✨</strong></h3><p>Inheritance allows us to pass down traits from a parent class to a child class, keeping our codebase DRY (Don’t Repeat Yourself). Think of it like a family recipe book where children inherit master recipes and add their own signature twists.</p><p><strong>Task 1: Animal Subclass Sound Overriding</strong></p><p><strong>Task</strong>: Create a base class Animal with attributes name and sound, and a method make_sound(). Create subclasses Dog and Cat that override make_sound() to print “Woof!” and “Meow!”.</p><p>class Animal:<br> # This sets up our base animal attributes<br> def __init__(self, name, sound):<br> self.name = name<br> self.sound = sound</p><p>def make_sound(self):<br> print(self.sound)</p><p>class Dog(Animal):<br> def __init__(self, name):<br> # This uses super() to inherit initialization from the parent Animal class<br> super().__init__(name, “Woof!”)</p><p># Instantiate and test our subclass<br>dog = Dog(“Bingo”)<br>dog.make_sound() # Output: Woof!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*iE7kI0SWj8u8sTFOfO33Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Enjdd3VBYJ0SDIYgylU8_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9C4JdX_obsQqJBVja-2L9Q.png" /></figure><p><strong>Detailed Explanation and Commentary: This illustrates how super().__init__()</strong> bridges our child class to the parent class, letting us inherit base setup logic without rewriting code. By extending Animal, our Dog class gains all parent capabilities while tailoring its own unique sound behavior.</p><p><strong>Task 2: Vehicle Hierarchy and Method Overriding</strong></p><p><strong>Task:</strong> Create a base class Vehicle with attributes brand and model, and a method display_info(). Create a subclass Car that adds doors and overrides display_info().</p><p>class Vehicle:<br> def __init__(self, brand, model):<br> self.brand = brand<br> self.model = model</p><p>def display_info(self):<br> print(f”Vehicle: {self.brand} {self.model}”)</p><p>class Car(Vehicle):<br> def __init__(self, brand, model, doors):<br> super().__init__(brand, model)<br> self.doors = doors</p><p>def display_info(self):<br> print(f”Car: {self.brand} {self.model}, Doors: {self.doors}”)</p><p># — — Execution — -<br>my_car = Car(“Toyota”, “Camry”, 4)<br>my_car.display_info()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwQbuwp2NEblSOCR9JtjtA.png" /><figcaption>v</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBCG4Yxxuaw190KJSDqxgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8BYhgUTQV2LtDOfODx1Nw.png" /></figure><p><strong>Detailed Explanation and Commentary: This demonstrates method overriding</strong> in inheritance, where a child class modifies an inherited method to present specialized information unique to its type.</p><h3><strong>Course 3: Iterators 🌀✨</strong></h3><p>An iterator acts like a bookmark in a massive book, allowing us to traverse through elements sequentially one item at a time without loading an entire collection into computer memory all at once.</p><p><strong>Task 1: Custom CountDown Iterator</strong></p><p>Task: Create a custom iterator class CountDown that takes a number n and counts down to 1 using __iter__() and __next__().</p><p>class CountDown:<br> def __init__(self, n):<br> self.n = n</p><p>def __iter__(self):<br> # This returns the iterator object itself to initiate the protocol<br> return self</p><p>def __next__(self):<br> # This yields the next sequential value or stops the iteration<br> if self.n &gt; 0:<br> val = self.n<br> self.n -= 1<br> return val<br> else:<br> raise StopIteration</p><p># — — Execution — -<br>for num in CountDown(3):<br> print(num)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*IHZCiuuWxZ_axsvS_qFSAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rslgd6n_UJkDwvnLDQchxw.png" /></figure><p><strong>Detailed Explanation and Commentary: This demonstrates how custom iterators</strong> maintain internal state across loop cycles. Every time the for loop requests an item, __next__() executes, decrementing our counter until it hits zero and raises StopIteration to exit cleanly.</p><p><strong>Task 2: List Iterator with Exception Handling</strong></p><p><strong>Task</strong>: Take a list of numbers [10, 20, 30, 40, 50], convert it into an iterator using iter(), and retrieve each element using next() while handling StopIteration gracefully.</p><p>numbers = [10, 20, 30, 40, 50]<br>my_iter = iter(numbers)</p><p>while True:<br> try:<br> # Retrieve items sequentially one by one<br> print(next(my_iter))<br> except StopIteration:<br> print(“Reached the end of the iterator safely!”)<br> break</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5P_nc47F016DP2S5pr2kWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KX9zvyjwanRasHj0awWDzQ.png" /></figure><p><strong>Detailed Explanation and Commentary: This illustrates how we process</strong> sequences element-by-element using explicit next() calls and catch the StopIteration exception to terminate our loop without crashing.</p><h3><strong>Course 4: Polymorphism 🎭✨</strong></h3><p>Polymorphism means “many forms”. It allows different classes to share identical method names while executing completely customized behaviors behind the scenes.</p><p><strong>Task 1: Bird Language and Consumer Function</strong></p><p><strong>Task:</strong> Create a base class Bird with speak(), subclasses Parrot and Crow that override it, and a function make_bird_speak() that accepts any bird object.</p><p>class Bird:<br> def speak(self):<br> return “Chirp”</p><p>class Parrot(Bird):<br> def speak(self):<br> return “Squawk”</p><p>def make_bird_speak(bird_obj):<br> # This polymorphically invokes .speak() without checking the object’s specific class type<br> print(bird_obj.speak())</p><p># — — Execution — -<br>make_bird_speak(Parrot()) # Output: Squawk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*Lqb7y-vrv3V9DY3E6QDB7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8exQWKAch6I4KveFwVFl7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSjBXXeRDBiztDBk3-CXEw.png" /></figure><p><strong>Detailed Explanation and Commentary: This highlights duck typing</strong>, where our consumer function relies entirely on the presence of the .speak() method rather than checking object classes explicitly. Polymorphism lets us write flexible, modular code that handles new subclasses effortlessly.</p><p><strong>Task 2: Polymorphic Vehicle Movement</strong></p><p><strong>Task: </strong>Create two classes Car and Bicycle with a move() method, store them in a list, and loop through them calling move().</p><p>class Car:<br> def move(self):<br> return “Car drives”</p><p>class Bicycle:<br> def move(self):<br> return “Bicycle pedals”</p><p># — — Execution — -<br>vehicles = [Car(), Bicycle()]<br>for v in vehicles:<br> print(v.move())</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vnjnlcyrh72Dg_55yfgcWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aajdcVcwjAiumitw64kCCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui3N1WbXr4LA1Y08-4gjUw.png" /></figure><p><strong>Detailed Explanation and Commentary: This demonstrates polymorphic iteration</strong>, allowing us to call identical method names across completely different classes without verifying their specific types beforehand.</p><h3><strong>Course 5: Variable Scope 🗺️✨</strong></h3><p>Scope dictates where variables live and can be accessed within our code, functioning much like personal drawers versus shared household tables.</p><p><strong>Task 1: Modifying Global State</strong></p><p><strong>Task: </strong>Create a global variable total = 0, and inside a function add_to_total(n), use the global keyword to modify it across multiple calls.<br># Initialize our global total tracker</p><p>total = 0</p><p>def add_to_total(n):<br> # This declares that we want to modify the global ‘total’ variable directly<br> global total<br> total += n<br> print(“Updated global total:”, total)</p><p># — — Execution — -<br>add_to_total(5)<br>add_to_total(10)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck9zgLa3RtYEBiaPonderQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COUmLmI3X1xCa6BPTw2aEw.png" /></figure><p><strong>Detailed Explanation and Commentary: This demonstrates how state persistence</strong> is achieved using the global keyword. Ordinarily, variables created inside functions are temporary; adding global total instructs Python to link our function directly to the module-level variable to accumulate running sums.</p><p><strong>Task 2: Nonlocal Keyword in Nested Functions</strong></p><p><strong>Task: </strong>Create a function outer() with a variable message = “Hi”, and inside it, create a nested function inner() that modifies message using the nonlocal keyword.</p><p>def outer():<br> message = “Hi”<br> <br> def inner():<br> # This modifies the enclosing variable from the parent scope<br> nonlocal message<br> message = “Hello from inner scope!”<br> <br> inner()<br> print(“Updated outer message:”, message)</p><p># — — Execution — -<br>outer()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXC26hrW0ZyHwe40H3OcWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2Jxygb-7JLD8dtt17cONA.png" /></figure><p><strong>Detailed Explanation and Commentary: This illustrates how the nonlocal keyword </strong>enables nested inner functions to mutate variables residing in their parent enclosing function without elevating them to global status.</p><h3><strong>Assignment &amp; Assessment Highlights 🚀📚</strong></h3><p><strong>Task 1: Instance Tracking with Class Variables</strong></p><p><strong>Task: </strong>Create a Counter class with a class variable to track total instances created, and print the count after making several objects.</p><p>class Counter:<br> # Class-level variable shared across all instances<br> total_instances = 0<br> <br> def __init__(self):<br> Counter.total_instances += 1</p><p># — — Execution — -<br>obj1 = Counter()<br>obj2 = Counter()<br>obj3 = Counter()<br>print(“Total instances created:”, Counter.total_instances)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zml5vOmcjbXBkK6vwMc_FA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbHYPPlBGL0F8gYg-kAaIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFsFjc3hShs0Eb4O21T1EA.png" /></figure><p><strong>Detailed Explanation and Commentary: This highlights class-level variables, </strong>which maintain a shared state across all generated instances to track cumulative counts rather than resetting per object.<br>Task 2: Polymorphic Shape Area Aggregation<br>Task: Create classes Rectangle, Circle, and Triangle with an area() method, store instances in a list, and calculate total area without checking types.<br>import math</p><p>class Rectangle:<br> def __init__(self, w, h):<br> self.w, self.h = w, h<br> def area(self):<br> return self.w * self.h</p><p>class Circle:<br> def __init__(self, r):<br> self.r = r<br> def area(self):<br> return math.pi * (self.r ** 2)</p><p># Store mixed shape instances in a single collection<br>shapes = [Rectangle(3, 4), Circle(2)]</p><p># Polymorphically sum up areas without checking individual object types<br>total_area = sum(shape.area() for shape in shapes)<br>print(f”Calculated Total Area: {total_area:.2f}”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcf97bRoENoAr2-7lwvPVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZeiAYKO9kvn-Gmpho9xYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFBIo3Xk6K2rowYLhZ3vmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4D-tWlLOnZGyJ1fQcUH7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwSyv-omYQlC7OWHoQdAVg.png" /></figure><p><strong>Detailed Explanation and Commentary: This illustrates polymorphic aggregation</strong>, enabling uniform processing of diverse object structures. Because every shape implements its own .area() method under a shared interface, our summation loop evaluates items seamlessly without conditional type checks.</p><p>What an incredible week of growth and discovery at DataraFlow! 🤗 I hope this deep dive into our exercises helps illuminate these core Python concepts for your own coding journey. Let me know which topic you would like us to explore next! ❤️✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f699b43ce34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>