🔁 Understanding Recursion with the Call Stack (Python) Recursion is when a function calls itself. To really understand what happens, visualize the call stack. Example: def show(n): if n == 0: return print(n) show(n - 1) print("END") show(3) Output: 3 2 1 END END END Call stack walkthrough: - show(3): prints 3, calls show(2) → Stack: [show(3)] - show(2): prints 2, calls show(1) → Stack: [show(3), show(2)] - show(1): prints 1, calls show(0) → Stack: [show(3), show(2), show(1)] - show(0): base case → return. As the stack unwinds, each function resumes and prints "END". That’s why "END" appears three times. Use cases: tree traversal (DFS), sorting (QuickSort/MergeSort), backtracking, filesystem traversal. Key takeaway: Recursion is powerful — always include a base case. #Python #Recursion #CallStack #Programming #Tech
Understanding Recursion with Call Stack in Python
More Relevant Posts
-
Python Sets Explained – Fast, Unique, and Powerful! # Definition: A Set in Python is an unordered collection of unique elements, used to store multiple items without duplicates. # Characteristics: - Unordered and unindexed - No duplicate elements - Mutable (add or remove items) - Elements must be immutable (int, string, tuple) - Supports union, intersection, and difference operations # Commonly Used Methods: add(), update(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), symmetric_difference(), copy() # Common Functions: len(), max(), min(), sum(), sorted(), any(), all() # LeetCode Problems: 217 Contains Duplicate 771 Jewels and Stones 136 Single Number 268 Missing Number 575 Distribute Candies 41 First Missing Positive 1207 Unique Number of Occurrence # Summary: Sets are efficient for removing duplicates, performing set operations, and optimizing comparison logic. LogicWhile #Python #Sets #PythonProgramming #Coding #ProblemSolving #LearnPython #DataStructures #LeetCode #DSA #CodeNewbie #SoftwareEngineer #Developer #CodingJourney #PythonLearning #Programming #100DaysOfCode #TechCommunity #LogicBuilding #CodingPractice #StudyWithMe #TechEducation #PythonBasics #Algorithms #CodeDaily #CodingLife #LearningInPublic
To view or add a comment, sign in
-
Using async in Python DOES NOT always make your code run faster... Synchronous code is like this: it 𝘮𝘶𝘴𝘵 finish task A before it can even 𝘵𝘩𝘪𝘯𝘬 about starting task B. If your code makes a network request, it may wait for the next 2-3 seconds, your CPU basically sitting idle. This is what asyncio is for. It lets you "pause" a task that's waiting and immediately switch to another task ready to run. But here's the catch: asyncio 𝗺𝗮𝗸𝗲𝘀 𝘆𝗼𝘂𝗿 𝗰𝗼𝗱𝗲 𝗳𝗮𝘀𝘁𝗲𝗿 𝗼𝗻𝗹𝘆 𝘄𝗵𝗲𝗻 𝗶𝘁'𝘀 𝗜/𝗢-𝗯𝗼𝘂𝗻𝗱 (𝘄𝗮𝗶𝘁𝗶𝗻𝗴), 𝗻𝗼𝘁 𝘄𝗵𝗲𝗻 𝗶𝘁'𝘀 𝗖𝗣𝗨-𝗯𝗼𝘂𝗻𝗱 (𝗰𝗮𝗹𝗰𝘂𝗹𝗮𝘁𝗶𝗻𝗴). • I/O-Bound: Your program is waiting for something EXTERNAL. Like: Making different API calls Reading multiple files from a network drive. • CPU-Bound: Your program is actively calculating something. Like: Training a machine learning model. Running complex transformations on a large pandas DataFrame. Also, asyncio operates on a single CPU core. Hence, It provides concurrency but not true parallelism. So, if your bottleneck is the CPU, asyncio won't help. You're looking for parallelism. You need to leverage multiple CPU cores, and that’s a job for Python's multiprocessing library. #python #asyncio #concurrency #parallelism #softwarearchitecture #backend #apis
To view or add a comment, sign in
-
Python Tip – Day 6: Make Your Loops Cleaner with enumerate() Ever used range(len()) to get both index and value in a loop? There’s a better and more Pythonic way , use enumerate()! Here’s a quick example: x = [1, 2, 3, 4, 5, 6] s = 0 for i in enumerate(x): print(i[0], i[1]) enumerate() returns both the index and value as a tuple! That’s why i[0] gives the index and i[1] gives the list element. Try unpacking it directly for cleaner code: for index, value in enumerate(x): print(index, value) enumerate() improves readability and makes your code look more professional. Keep your loops clean and efficient! #Python #30DaysOfpythonCode #PythonTips #CodingJourney #LearnPython #CodeBetter
To view or add a comment, sign in
-
-
Practicing Python by building 3 small projects I’ve been focusing on core Python concepts by shipping tiny command-line apps. Nothing fancy, just real reps. 1) Number Guessing Game Computer picks a number 1–100 → you guess. Feedback after each try: Too high / Too low / Correct. Concepts: input handling, random, loops, guardrails. 2) Rock–Paper–Scissors Play vs the computer; r/p/s inputs, q to quit. Keeps track of wins/losses/ties with clear prompts. Concepts: branching, simple state, replay loop. 3) Python Trivia Quiz 5 random questions from a small in-memory set. Case-insensitive answers, instant feedback, final score /5. Concepts: dicts, random sampling, string ops. I’ll post the GitHub link in the comments. If you have ideas for the next small project. I’m all ears. #Python #LearningInPublic #DevOps #Automation #BeginnerProjects #BuildNotWatch
To view or add a comment, sign in
-
🚨 Stop killing your Python performance with string concatenation! I see this mistake everywhere: ❌ The slow way (O(n²)) result = "" for word in words: result += word # Creates a NEW string every time! Here's what's actually happening: Every += creates an entirely new string in memory, copying all previous characters. Process 1000 strings? That's ~500,000 character copies. Ouch. The fix is beautifully simple: # ✅ The fast way (O(n)) result = [] for word in words: result.append(word) # Just adds to list return ''.join(result) # Single concatenation at the end Why it matters: → Strings are immutable in Python → Lists are mutable and efficient for building → One final join operation vs thousands of copies → Can be 100x+ faster on large datasets Real impact: I've seen this single change cut processing time from minutes to seconds in production code. Pro tip: For simple cases, list comprehensions + join are even cleaner: result = ''.join([word for word in words]) What's your favorite Python performance trick? #Python #Programming #SoftwareEngineering #CodingTips #PerformanceOptimization #CleanCode #TechTips #PythonProgramming #SoftwareDevelopment #CodeEfficiency
To view or add a comment, sign in
-
🚀 𝐏𝐲𝐭𝐡𝐨𝐧 𝟑.𝟏𝟒 - 𝐓𝐡𝐞 𝐧𝐞𝐰 𝐅𝐫𝐞𝐞-𝐓𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠 𝐦𝐨𝐝𝐞𝐥 𝐚𝐧𝐝 𝐰𝐡𝐲 𝐢𝐭 𝐦𝐚𝐭𝐭𝐞𝐫𝐬 🚀 If you’ve been writing Python for a while, you’ve probably bumped into the limitations of the Global Interpreter Lock (GIL). The GIL means that even on a multi-core machine, threads in one Python process can’t execute Python bytecode truly in parallel. Only one thread runs at a time ! With Python 3.14, the “𝒇𝒓𝒆𝒆-𝒕𝒉𝒓𝒆𝒂𝒅𝒆𝒅” or “no-GIL” build is officially supported. That means you can opt-into a version of CPython where the GIL is disabled and threads can truly run in parallel across multiple CPU cores. ⚠️𝐖𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐆𝐈𝐋? In previous Python versions, the Global Interpreter Lock (GIL) ensured only one thread could really execute Python bytecode at a time, so even on multi‐core hardware, threads couldn’t fully run in parallel. 💡𝐖𝐡𝐚𝐭 𝐜𝐡𝐚𝐧𝐠𝐞𝐬 𝐰𝐢𝐭𝐡 𝐟𝐫𝐞𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠? - Threads can now truly run in parallel on multiple cores when using a free-threaded build of Python (python3.14t) - This opens up real gains for CPU-bound, multithreaded Python workloads. - Existing Python libraries written in thread-safe way, should work without modification and utilize all cores of CPU. - C extension that has not been explicitly marked as free-thread-safe, it will re-enable the GIL for the lifetime of that process. 🔍𝐁𝐨𝐭𝐭𝐨𝐦 𝐥𝐢𝐧𝐞 If your Python apps care about multi-core performance or threading, this update is worth watching (or even experimenting with). It’s a strong signal that Python is leveling up its concurrency game, and making it easier for developers to build more scalable, high-performance systems. #Python #Python314 #Concurrency #Multithreading #GIL #SoftwareEngineering #DevCommunity
To view or add a comment, sign in
-
-
🔁 How Python Functions Can Remember Their State (Closures Explained Simply) I recently came across this elegant little Python snippet 👇 def counter(): count = 0 def increment(): nonlocal count count = count + 1 return count return increment increment = counter() Now, every time you call increment(), it “remembers” the previous value of count — even though counter() has already finished running! ✅ Output for 3 instances of print print(increment()) # 1 print(increment()) # 2 print(increment()) # 3 This works because of closures — inner functions that “capture” variables from their enclosing scope. The keyword nonlocal tells Python to use the outer variable instead of creating a new one. In plain English: You’ve just built your own counter that remembers its history without using a global variable. Pretty neat, right? 😊
To view or add a comment, sign in
-
🚀 Python Tip of the Day Ever wondered how to handle multiple conditions cleanly in one line? Check out this elegant one-liner that decides the discount type based on the customer’s tier 👇 # Decide discount type based on customer type customer = {"type": "Gold"} discount_type = ( "Platinum Discount" if customer["type"] == "Platinum" else "Gold Discount" if customer["type"] == "Gold" else "Silver Discount" if customer["type"] == "Silver" else "Regular Discount" ) print(discount_type) 💡 Output: Gold Discount What’s Happening: Each condition is checked in order — Python picks the first one that’s true! It’s a clean way to replace multiple if-elif-else blocks when your logic is short and simple. #Python #CodingTips #SoftwareDevelopment #100DaysOfCode #PythonDeveloper #LearningPython
To view or add a comment, sign in
-
PYTHON JOURNEY - Day 15 / 50 !! TOPIC : break, continue, and pass in Python Loops are powerful — but sometimes you need to control their flow. That’s where break, continue, and pass come in --- 1. break → Stop the loop immediately for i in range(1, 6): if i == 3: break print(i) Output: 1 2 Use when you want to exit the loop early. --- 2. continue → Skip to the next iteration for i in range(1, 6): if i == 3: continue print(i) Output: 1 2 4 5 Use when you want to skip certain conditions. --- 3. pass → Do nothing (acts as a placeholder) for i in range(1, 4): if i == 2: pass # Placeholder for future code print("Number:", i) Output: Number: 1 Number: 2 Number: 3 --- Quick Tip: break → stop continue → skip pass → placeholder Mastering these gives you full control over loops! --- #Python #LearnPython #Coding #Programming #PythonBasics #BreakContinuePass #LinkedInLearning
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