Day 13 of my Python learning journey Today I worked on a classic problem that looks simple, but teaches a very powerful idea. Problem: Sort 0s, 1s, and 2s (Dutch National Flag Problem) Given an array containing only 0, 1, and 2, sort it in-place. Example: arr = [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2] What I learned today: Instead of using sorting functions, we can solve this in one pass using pointers. This problem is known as the Dutch National Flag problem. What is Dutch National Flag idea? This concept was given by Edsger Dijkstra. The idea comes from the Dutch flag, which has three colors: Red, White, Blue We map them like this: 0 → Red 1 → White 2 → Blue So the goal is to arrange elements in this order, just like the flag. How the logic works: We divide the array into three parts: Left → all 0s Middle → all 1s Right → all 2s And we maintain three pointers: low → where 0 should go mid → current element high → where 2 should go Code I wrote: arr = [2, 0, 2, 1, 1, 0] low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[high] = arr[high], arr[mid] high -= 1 print(arr) Problems I faced while coding this: At first I tried using sort(), but that defeats the purpose of the problem. I was confused about why we use three pointers instead of two. The condition mid <= high was tricky to understand. I also made mistakes while swapping, which broke the logic. What I finally understood: This algorithm processes each element only once. We don’t need extra space and no nested loops. Time and Space Complexity: Time Complexity: O(n) → single pass through the array Space Complexity: O(1) → in-place sorting Question: Why do we not increase mid when we swap with high? Today’s realization: Some problems are not about coding more, but about thinking in the right structure. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
Dutch National Flag Problem: In-Place Sorting with Three Pointers
More Relevant Posts
-
Day 12 of my Python learning journey Today I tried solving a problem that felt like an extension of Two Sum, but it was a bit more tricky. Problem: 3 Sum (using Two Pointers) Given an array, find all unique triplets such that their sum is equal to 0. Example: arr = [-1, 0, 1, 2, -1, -4] Output: [[-1, -1, 2], [-1, 0, 1]] What I learned today: Instead of checking all possible triplets (which is slow), we can: Sort the array first Fix one element Use Two Pointers to find the other two numbers How it works: Fix one number arr[i] Start left from i+1 Start right from the end Check the sum of three numbers • If sum is too small → move left pointer • If sum is too large → move right pointer • If sum is 0 → store the triplet Code I wrote: arr = [-1, 0, 1, 2, -1, -4] arr.sort() result = [] for i in range(len(arr) - 2): if i > 0 and arr[i] == arr[i - 1]: continue left = i + 1 right = len(arr) - 1 while left < right: s = arr[i] + arr[left] + arr[right] if s == 0: result.append([arr[i], arr[left], arr[right]]) while left < right and arr[left] == arr[left + 1]: left += 1 while left < right and arr[right] == arr[right - 1]: right -= 1 left += 1 right -= 1 elif s < 0: left += 1 else: right -= 1 print(result) Problems I faced while coding this: At first I tried using three nested loops, but it became too slow. I did not understand why sorting is necessary. I got duplicate triplets and didn’t know how to remove them. The duplicate skipping logic with while loops confused me a lot. What I finally understood: Sorting helps us use the Two Pointer technique and also makes it easier to avoid duplicates. This approach reduces complexity from O(n³) to O(n²). Time and Space Complexity: Time Complexity: O(n²) → one loop + two pointer traversal Space Complexity: O(1) (excluding the output list) Question: Why do we skip duplicates using: if i > 0 and arr[i] == arr[i - 1]: Today’s realization: Some problems look like small extensions, but the logic becomes much deeper. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🔹 I recently explored how strings work in Python and how small syntax choices can make code more readable and efficient 👇 🔹 Blog Summary In this blog, I explain how Python allows strings to be defined using single quotes, double quotes, and triple quotes. I also cover when to use each approach, especially for multi-line text and writing clean, maintainable code. 🔹 Key Learnings ✔ Gained clarity on different ways to define strings in Python ✔ Learned how to handle quotes within strings effectively ✔ Understood the importance of readability in real-world coding #Python #DataStructures #MachineLearning #AI #LearningInPublic #Coding #Tech A heartfelt thanks to Vishwanath Nyathani, Raghu Ram Aduri, Kanav Bansal, and, Mayank Ghai, along with my mentors Harsha M. for their continuous guidance and motivation. Innomatics Research Labs
To view or add a comment, sign in
-
For experienced developers, AI tools like JetBrains AI and PyCharm's code completion features are workflow game-changers. But for Python beginners, are these powerful tools creating a dependency that hinders real skill acquisition? We explore the paradox of features like local code completion and next edit suggestions, and discuss why stepping back from AI assistance might be the most effective way to learn Python. Great learning often comes from identifying – and fixing – mistakes. Read our take and find out how to customize your PyCharm experience for better learning: https://jb.gg/90ime3 #PythonLearning #DeveloperSkills #TechEducation #AIinCoding
To view or add a comment, sign in
-
🧠 Python Tricky Outputs — Test Your Knowledge! Can you guess the output of these three Python snippets? Let's find out! 👇 🔍 OUTPUTS: Snippet 1 → '['a', 'b', 'c', 'd', 'e', 'f,g,h']' Snippet 2 → '{2, 3}' Snippet 3 → '2' 🔍HOW IT WORKS: "Snippet 1 — split() with maxsplit=5" Step 1 → String: "a,b,c,d,e,f,g,h" Step 2 → Split by comma ',' Step 3 → maxsplit=5 means only split the first 5 times. Step 4 → Result has 6 items (5 splits + remainder) Split 1 → "a" Split 2 → "b" Split 3 → "c" Split 4 → "d" Split 5 → "e" Remainder → "f,g,h" (no more splitting) "Snippet 2 — Set Intersection (&)" Step 1 → {1, 2, 3} Step 2 → {2, 3, 4} Step 3 → & (ampersand) finds common elements. Step 4 → Common elements: 2 and 3 Step 5 → Result: {2, 3} "Snippet 3 — dict.get() with default" Step 1 → Dictionary d = {"a": 1} Step 2 → d.get("b", 2) Step 3 → "b" is NOT a key in the dictionary Step 4 → get() returns default value → 2 Step 5 → If the key existed, it would return the actual value ⚠️ EDGE CASES: "split() maxsplit" maxsplit=0 → No splitting → Entire string as one item maxsplit > number of commas → Splits all, extra maxsplit ignored Empty string → [''] "Set intersection" Empty set → {} No common elements → set() Same sets → Returns the set itself "dict.get()" Key exists → Returns actual value Key missing → Returns default No default provided → Returns None 📌 REAL-WORLD APPLICATIONS: "split() with maxsplit" → Parsing logs, CSV headers, first N fields only "Set intersection" → Finding common users, shared interests, mutual friends "dict.get()" → Safe dictionary access, avoiding KeyError, from defaults 💡 KEY CONCEPTS: • 'split(',', maxsplit)' → Maximum number of splits to perform • '&' operator → Set intersection (common elements) • 'dict.get(key, default)' → Returns default if key missing • No KeyError → Safer than dict[key] 📌 QUICK QUIZ — Test Yourself: # Q1: What's the output? print("one,two,three,four".split(',', 2)) # Q2: What's the output? print({5, 6, 7} & {6, 7, 8}) # Q3: What's the output? d = {"name": "Alice"} print(d.get("age", 25)) #Python #Coding #Programming #LearnPython #Developer #Tech #PythonTips #Dictionary #Sets #Strings #CodeQuiz #SplitMethod #SetOperations #GetMethod #Day76
To view or add a comment, sign in
-
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
Most people quit learning Python halfway through a tutorial. Not because it's too hard. Because solving fake problems on fake datasets feels pointless. Here's what worked for me: I stopped treating Python like a subject to study and started treating it like a game to beat. Games give you context that tutorials don't. You're not learning "while" loops to pass a quiz. You're learning them to make your robot escape a dungeon or your spaceship dodge asteroids. Same syntax. Totally different motivation. Here are the games that taught me Python without feeling like school: ➡️ CheckiO (checkio.org) Coding challenges disguised as island missions. You unlock levels by solving puzzles with Python. Before you know it, you've mastered loops and conditionals. ➡️ CodinGame (codingame.com) Build AI bots that compete in real-time multiplayer games. Your code controls racing cars, battle droids, and strategy units. Addictive and practical. ➡️ Python Challenge (pythonchallenge.com) A riddle game where every level requires Python to crack. Cryptic, frustrating, and weirdly satisfying when you finally solve it. Teaches problem-solving, not memorization. ➡️ Code Combat (codecombat.com) Fantasy RPG where you write Python to control your character. Move, attack, cast spells — all through code. Works for beginners and advanced players. ➡️ Screeps (screeps.com) MMO strategy game where you program your colony. Automate resource gathering, defense, and expansion. High learning curve, insanely rewarding once it clicks. The reason these work better than tutorials? They give you a reason to care. Tutorials teach syntax in isolation. Games teach syntax in context. You remember "for" loops because you needed them to make your robot move faster. You remember list comprehensions because they helped you filter enemies in battle. Same Python. Better reason to keep going. Shoutout to Karina Samsonova for her SQL game list - she nailed this concept. Dry exercises kill motivation. Games make the syntax stick because the problems feel real, even if they're wrapped in a murder mystery or a space battle. If you've been stuck halfway through a Python tutorial (or avoiding starting at all), try a game instead. Pick one. Play for 30 minutes. You'll be writing code without realizing you're learning. #sql #python #coding
To view or add a comment, sign in
-
Tell your AI that you are beginner when learning Python! I recently asked AI to generate some simple code to reverse two virtual spreadsheet columns called ‘Name’ and ‘Type’. Instead of simply suggesting code in which the column list [‘Name’, ‘Type] is replaced by [‘Type’, ‘Name’], AI suggested a complex indexing trick that looks like [::-1]. Succinct coding, to be sure, but I could not decipher it without additional prompts! In another case, my AI provided some sample code in which a variable was defined after that variable was used! The Horror! When I asked why it made such a fundamental mistake, the AI complimented me on my “good eye” for catching the error and that it did not necessarily provide code in execution order. So, if you are just learning Python, always start your session with a good prompt to set the stage such as the following: "I am a total beginner learning Python. Please follow these rules for ALL Python code you write for me: 1. Write code in execution order. 2. Break every task into small, discrete steps. 3. Use simple, obvious variable names that describe what they contain 4. Add plenty of comments explaining what it happening in plain English 5. Avoid shortcuts, clever one-liners, or condensed syntax that experienced coders use 6. If there are multiple ways to do something, choose the most readable one, not the most efficient one 7. Before showing me code, double-check it runs in the correct order from top to bottom" For more tips, consider my new book "Automate Excel with Python". My publisher @No Starch Press is offering a free review chapter in case you were interested: https://lnkd.in/eS-WAVyV Good luck and good coding! #Excel, #Python, #pandas, #dataframes,#Productivity, #DataAnalysis, #Automation
To view or add a comment, sign in
-
-
⚠️ Python Gotcha — The Mutable Default Argument Trap! This code looks innocent, but behaves surprisingly. Can you guess the output? 🔍 WHAT MOST BEGINNERS EXPECT: print(add_item(1)) → [1] print(add_item(2)) → [2] ⚠️ WHAT ACTUALLY HAPPENS: print(add_item(1)) → [1] print(add_item(2)) → [1, 2] 😲 🔍 WHY THIS HAPPENS: Step 1 → Default arguments are created ONCE when the function is defined Step 2 → Not created each time the function is called Step 3 → 'lst = []' creates a single list that persists Step 4 → Every call shares the SAME list object Step 5 → First call → [1] Step 6 → Second call → [1, 2] Step 7 → Third call → [1, 2, 3] and so on... ✅ HOW TO FIX IT: def add_item(item, lst=None): if lst is None: lst = [] lst.append(item) return lst print(add_item(1)) # [1] print(add_item(2)) # [2] ⚠️ EDGE CASES: Multiple calls → List keeps growing unexpectedly Different arguments → Still shares the same list Function used elsewhere → Unexpected side effects Debugging nightmare → Hard to trace where the list changed 📌 REAL-WORLD APPLICATIONS: 🐛 Debugging → Understanding unexpected behavior 📚 Learning → Teaching Python fundamentals ✅ Code Reviews → Catching this common mistake 🔧 Best Practices → Always use None as the default for mutable types 📝 Interviews → Classic Python interview question 💡 KEY CONCEPTS: • Default arguments → Evaluated once at function definition • Mutable objects → Lists, dictionaries, and sets behave this way • Immutable objects → Integers, strings, and tuples are safe • None as default → Standard workaround pattern • Object reference → Same memory location shared • Side effects → Unexpected modifications 📌 QUICK CHECK: What will this print? def add_item(item, lst=[]): lst.append(item) return lst print(add_item(1)) print(add_item(2)) print(add_item(3)) Answer: [1] → [1, 2] → [1, 2, 3] 👇 Drop your experience — have you ever faced this bug? #Python #PythonGotchas #Coding #Programming #LearnPython #Developer #Tech #Debugging #PythonTips #CommonMistakes #MutableDefaultArguments #Day75
To view or add a comment, sign in
-
-
Three months ago, our agent cited Python 3.13 as the latest stable release in a research report. It was wrong — 3.12 was current at the time. The factcheck caught it. Corrected the report. That part isn't remarkable. Any review process would catch that. What happened next is the part that matters: the agent stored a lesson. Not the corrected fact — the lesson about the mistake itself. "Always verify version numbers against the official release page. Don't rely on training data for anything with a release cycle." Two weeks later, I asked it to research a completely different tool. The vector memory surfaced that lesson during pre-search. The agent went straight to the official changelog before writing a single sentence about version compatibility. Nobody told it to. It remembered why it had been wrong before. This is the self-improvement loop I've been building toward in this series. Previous posts covered the infrastructure — four memory types, four storage systems, routing, retrieval. This post is about what it enables: an agent that gets better without being retrained. The loop: 1. Agent produces output 2. Factcheck or human review finds an error 3. The correction gets saved — not just the right answer, but the lesson: what went wrong and how to avoid it 4. Next time, pre-search surfaces the lesson before the agent starts working The key word is "lesson." We don't store "Python 3.12 is correct." We store "version numbers from training data are unreliable — always check the source." One is a fact that expires. The other is a behavior that compounds. The same loop runs on human feedback. I told the agent: "Don't mock the database in integration tests." Instead of losing that correction after the session, the agent saved it with structure — what was corrected, why it was wrong, how to apply it in the future. That's a feedback memory. Next time it writes integration tests — in any project, any session — it retrieves the lesson and applies it. Over time, these accumulate into working knowledge about how to do the job correctly. Does it work? In the first 20 research sessions, the agent averaged 3.2 factcheck corrections per report. After 80+ sessions with the lesson loop: 0.8. Not zero. But the same category of mistake rarely happens twice. Version numbers, citation formats, API accuracy — each corrected once, stored as a lesson, applied going forward. No fine-tuning, no retraining. The model is the same. The memory layer is what improved. The deeper insight: the agent doesn't just store information. It stores lessons about how to handle information. Facts expire. Lessons compound. What's the most repeated mistake your agent makes — the one you keep correcting but it never sticks? #AIAgents #AgentArchitecture #SelfImprovingAI
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development