DAY 9 – Python Revision | Recursion Masterclass (Core Logic Building) #Python #Recursion #LogicBuilding #FAANGPrep #DSA Recursion means a function calling itself until a base condition stops it. Ye technique har FAANG interview ka core hoti hai, specially: Tree problems Backtracking Divide & Conquer Dynamic Programming Aaj ke 4 powerful recursion problems 👇 (clean code + explanation) 🧩 Problem 1 — Factorial using Recursion (Base Concept) Input: 5 Output: 120 ✔ Recursion Logic Base case → n == 0 → return 1 Recursive case → n * factorial(n-1) def factorial(n): if n == 0: return 1 return n * factorial(n - 1) print(factorial(5)) Output: 120 🧩 Problem 2 — Fibonacci Using Recursion (Interview Favorite) Input: 6 Output: 8 ✔ Recursion Logic Fib(n) = Fib(n-1) + Fib(n-2) def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) print(fib(6)) Output: 8 🧩 Problem 3 — Sum of Digits Using Recursion (Logic Booster) Input: 1234 Output: 10 ✔ Recursion Logic Base → jab number 0 ho Recursive → last digit add + remaining digits ka sum def sum_of_digits(n): if n == 0: return 0 return (n % 10) + sum_of_digits(n // 10) print(sum_of_digits(1234)) Output: 10 🧩 Problem 4 — Reverse a String Using Recursion (Amazon) Input: "hello" Output: "olleh" ✔ Recursion Logic Base → length 0 or 1 Recursive → last char + reverse of remaining string def reverse_string(s): if len(s) <= 1: return s return reverse_string(s[1:]) + s[0] print(reverse_string("hello")) Output: olleh
Python Recursion Masterclass: Core Logic Building
More Relevant Posts
-
Ever been confused why sometimes comparing two things in Python gives a weird result, or why identical looking lists are suddenly "not equal"? I was stuck on this for hours yaar when learning about object identity versus value. It's a common beginner pitfall that can lead to unexpected bugs. Understanding `is` versus `==` is super important for writing correct Python code. Here's a quick breakdown: - `==` (Equality operator): This checks if the *values* of two objects are the same. It compares what's inside the objects. - `is` (Identity operator): This checks if two variables refer to the *exact same object* in memory. Think of it as checking if they point to the same storage location. - For immutable types like integers and strings, Python often optimizes by using the same object for identical values within a certain range. For example, `a = 500; b = 500; print(a is b)` might be `False` because 500 is outside the optimized range (-5 to 256). - However, for `a = 10; b = 10; print(a is b)`, it will usually be `True` because `10` is a small integer, often cached. It's a memory optimization. - When you create two separate lists, even if they have the same elements, they are distinct objects in memory. `list1 = [1, 2]; list2 = [1, 2]; print(list1 == list2)` will be `True`, but `print(list1 is list2)` will be `False`. Knowing this difference helps debug a lot of subtle issues, especially when working with mutable objects like lists and dictionaries. What other Python quirks have you found tricky? #Python #PythonTips #BeginnerPython #CodingIndia #Freshers
To view or add a comment, sign in
-
Understanding Regular Expressions in Python Regular Expressions (RegEx) are powerful tools used for searching, matching, and manipulating text. In Python, they are handled using the built-in re module. Why use RegEx? • Validate inputs (emails, phone numbers, passwords) • Search for specific patterns in text • Extract useful data from large datasets • Replace or clean text efficiently Key Functions in Python RegEx: • re.search() → Finds first match • re.findall() → Finds all matches • re.sub() → Replaces text • re.match() → Matches from beginning Final Thought: Mastering Regular Expressions can significantly boost your data processing and text handling skills as a developer. Thanks for : Sultan AL-Yahyai CodeAcademy_om Kulsoom Shoukat Ali #Python #Programming #DataAnalysis #Coding #RegularExpressions #TechSkills #Learning #Developers
To view or add a comment, sign in
-
-
🚀 Python Series – Day 6: Conditional Statements (if-else) Till now, we learned how to take input and use operators 💻 But how does a program make decisions? 🤔 👉 Using Conditional Statements 🔥 🧠 What is a Condition? A condition checks whether something is True or False ✅ Basic if Statement age = 18 if age >= 18: print("You are eligible to vote") 🔁 if-else Statement age = int(input("Enter your age: ")) if age >= 18: print("Eligible") else: print("Not Eligible") 🔄 if-elif-else (Multiple Conditions) marks = int(input("Enter marks: ")) if marks >= 90: print("Grade A") elif marks >= 75: print("Grade B") elif marks >= 50: print("Grade C") else: print("Fail") ⚠️ Important Rule 👉 Indentation matters in Python! Incorrect: if age >= 18: print("Eligible") Correct: if age >= 18: print("Eligible") 🎯 Why is this important? ✔ Used in decision making ✔ Used in real-world logic ✔ Used in every program ❓ Question for you: What will be the output? x = 10 if x > 5: print("A") elif x > 8: print("B") else: print("C") 👉 Comment your answer 👇 📌 Tomorrow: Loops (for & while) 🔥 #Python #Coding #DataScience #Programming #LearnPython #Beginners #Tech #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
🚀 Day 8 of DSA / Python Practice Today was all about string manipulation and validation logic — basic on the surface, but these are the exact patterns used in real interviews and production code. 🔹 What I practiced: 1️⃣ Removing unwanted characters Removed spaces manually using loops Built reusable functions instead of one-off code 👉 Example 1: "he ll o" → "hello" 👉 Example 2: " a b c " → "abc" 2️⃣ Filtering characters (Vowels removal) Focused on condition-based filtering 👉 Example 1: "satyalakshmi" → "stylkshm" 👉 Example 2: "HELLO" → "HLL" 3️⃣ String Reversal (2 approaches) Logic-based reversal (building from front) Index-based reversal (reverse traversal) 👉 Example 1: "HELLO" → "OLLEH" 👉 Example 2: "Python" → "nohtyP" 4️⃣ Handling spaces + reversing Removed spaces first, then reversed 👉 Example 1: "he ll o" → "olleh" 👉 Example 2: "a b c d" → "dcba" 5️⃣ Character classification Counted uppercase, lowercase, digits, special characters 👉 Example 1: "Abc@123" → Upper:1, Lower:2, Digits:3, Special:1 👉 Example 2: "Hi#9K" → Upper:2, Lower:1, Digits:1, Special:1 6️⃣ Password strength checker Applied real-world validation logic 👉 Example 1: "abc123" → Weak 👉 Example 2: "Abc@1234" → Strong 7️⃣ Duplicate detection using sets (important concept) Efficient tracking using seen and duplicate 👉 Example 1: "aabbccde" → ['a','b','c'] 👉 Example 2: "programming" → ['r','g','m'] 📌 Code available on my GitHub :https://lnkd.in/dCYNAqKN #Day8 #Python #DSA #CodingJourney #ProblemSolving 10000 Coders sanjeev ch Mrinal Sarkar
To view or add a comment, sign in
-
1️⃣ Two Sum Problem: Given an array of integers and a target number, return the indices of two numbers that add up to the target. Example: Input: [2,7,11,15], target = 9 Output: [0,1] Python Example Code Python def twoSum(nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j] 2️⃣ Palindrome Number Problem: Check whether a number reads the same forward and backward. Example: 121 → True 123 → False Python def isPalindrome(x): return str(x) == str(x)[::-1] 3️⃣ Fizz Buzz Problem: Print numbers from 1 to n: Multiples of 3 → Fizz Multiples of 5 → Buzz Multiples of both → FizzBuzz Python def fizzBuzz(n): result = [] for i in range(1, n+1): if i % 15 == 0: result.append("FizzBuzz") elif i % 3 == 0: result.append("Fizz") elif i % 5 == 0: result.append("Buzz") else: result.append(str(i)) return result 4️⃣ Valid Parentheses Check if brackets are correctly closed. Example: ()[]{} → True (] → False
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
-
Python functions with fixed signatures break the moment you need to forward arguments across abstraction boundaries. *args and **kwargs solve that — and this python tutorial goes well past the syntax. — How CPython actually handles variadic calls at the C level (PyTupleObject, PyDictObject, and why there's a real allocation cost) — Why a defaulted parameter before *args is effectively unreachable via positional calling — and the idiomatic fix — The difference between *args isolating the mapping vs sharing mutable values inside it — ParamSpec (PEP 612) for preserving decorator signatures through the type system — TypedDict + Unpack (PEP 692, Python 3.12) for per-key precision on **kwargs — inspect.Parameter.kind for reading variadic signatures at runtime — the foundation of FastAPI and pytest's dispatch logic — Lambda variadic syntax, functools.wraps, kwargs.setdefault patterns, and common SyntaxErrors caught at parse time Includes interactive quizzes, spot-the-bug challenges, a design decision review, and a 15-question final exam with a downloadable certificate of completion. Full guide: https://lnkd.in/gHkdvCn5 #Python #PythonProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
✅ *Core Python Interview Questions With Answers* 🐍 1 What is Python - Interpreted, high-level programming language - Created by Guido van Rossum in 1991 - Used for web dev, data analysis, automation, AI 2 What is an interpreter - Executes code line-by-line without compilation - Python uses CPython as default interpreter - Faster for development, slower runtime than compiled languages 3 What are variables - Named storage for data values - Dynamically typed: type inferred at runtime - Example: age = 30 #(int) name = "Bonus" #(str) 4 What are data types - Built-in types: int, float, str, bool, list, tuple, dict, set - Mutable: list, dict, set (can change contents) - Immutable: int, str, tuple (cannot change after creation) 5 What is a list - Ordered, mutable collection of items - Allows duplicates, indexed from 0 - Example: customers = ["A", "B", "A"] 6 What is a dictionary - Unordered key-value pairs (ordered since Python 3.7) - Keys unique, values any type - Example: user = {"id": 1, "name": "Bonus"} 7 Difference between list and tuple - List mutable [], Tuple immutable () - List slower, Tuple faster and hashable - Use tuple for fixed data like coordinates 8 What are loops - For: iterate sequences (for i in range(5)) - While: condition-based (while x < 10) - Used for repeating tasks efficiently 9 What are functions - Reusable code blocks defined with def - Can take parameters, return values - Example: def greet(name): return f"Hello {name}" 10 Interview tip you must remember - Always explain with code example - Discuss time complexity (O(1), O(n)) - Practice on LeetCode for data roles
To view or add a comment, sign in
-
🎉 Released my first Python package! 🎉 An open-source Python library for imbalanced classification, now available on PyPI. Existing oversampling methods (SMOTE and its variants) operate in feature space without geometric guarantees: they interpolate between neighbours, but make no commitments about where synthetic points land relative to class boundaries or the minority distribution's internal structure. circover addresses this through four contributions: NHOP (Normalised Histogram Overlap Percentage), a distribution fidelity metric grounded in the identity NHOP = 1 − TV, where TV is total variation distance. Provides per-feature and global scores for evaluating synthetic data quality against the original distribution. ✔️ GeometricSeedSelector: combines NHOP, average geometric topology preservation (AGTP), Jensen–Shannon divergence, and a z-score criterion to select oversampling seeds that maximally preserve minority class geometry. GVM-CO / LRE-CO / LS-CO, three oversampling algorithms that generate synthetic points on geometry-constrained regions (circles, Voronoi-clipped disks, annular layers), with angular bias toward a gravity center derived from local density and inter-cluster distance. All three are fully compatible with imbalanced-learn pipelines and sklearn cross-validation. ✔️ DegradationBench: a controlled benchmark protocol that removes minority samples in equal increments (0% → 100%) and evaluates any estimator or pipeline via cross-validation at each level. Summarised by the Area Recovery Index (ARI = ∫ score(δ) dδ), enabling rigorous comparison across methods. 💻 pip install circover 💻 Feedback and collaboration from the imbalanced learning community are welcome. #MachineLearning #Python #OpenSource #ScientificComputing #ImbalancedLearning #DataScience
To view or add a comment, sign in
-
✅ Python Interview Questions with Answers 🐍💻 1️⃣ Reverse a string without using [::-1] python def reverse_string(s): return ''.join(reversed(s)) print(reverse_string("hello")) # Output: "olleh" 2️⃣ Count frequency of elements in a list python from collections import Counter data = [1, 2, 2, 3, 3, 3] counts = Counter(data) print(counts) # Output: {3: 3, 2: 2, 1: 1} 3️⃣ Check if two strings are anagrams python def is_anagram(s1, s2): return sorted(s1) == sorted(s2) print(is_anagram("listen", "silent")) # Output: True 4️⃣ Find duplicates in a list python def find_duplicates(lst): return list(set([x for x in lst if lst.count(x) > 1])) print(find_duplicates([1, 2, 2, 3, 4, 4])) # Output: [2, 4] 5️⃣ Lambda function to square numbers in a list python nums = [1, 2, 3, 4] squared = list(map(lambda x: x**2, nums)) print(squared) # Output: [1, 4, 9, 16] 📍Stay connected with Ravi Kiran Chintakayala for more
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